package com.photoeditor.demo.ui.activity.edit;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.gpuimage.AdjustGPUImageView;
import com.android.gpuimage.GPUImage;
import com.android.gpuimage.GPUImageFilter;
import com.android.graffiti.GraffitoView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.common.commercialize.reward.RewardAdManager;
import com.common.commercialize.sdk.CommercializeSDK;
import com.common.commercialize.utils.TaskRunnable;
import com.photoeditor.R;
import com.photoeditor.demo.ad.AdKeyConstant;
import com.photoeditor.demo.ad.EditCompleteAdProvider;
import com.photoeditor.demo.ad.MainReturnAdProvider;
import com.photoeditor.demo.app.ActionConstant;
import com.photoeditor.demo.app.AppApplication;
import com.photoeditor.demo.app.TestUser;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterCategoryBean;
import com.photoeditor.demo.db.MagazineBean;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.UseEffectInfo;
import com.photoeditor.demo.model.bean.BitmapBean;
import com.photoeditor.demo.model.bean.EditEmojiBean;
import com.photoeditor.demo.model.bean.EmojiBean;
import com.photoeditor.demo.model.bean.stash.ContainerBean;
import com.photoeditor.demo.model.bean.stash.DateStickerBean;
import com.photoeditor.demo.model.bean.stash.TextBean;
import com.photoeditor.demo.model.bean.stash.TimeStickerBean;
import com.photoeditor.demo.model.event.ExitAddTextFuntionEvent;
import com.photoeditor.demo.model.event.FilterDetailUnlockSuccess;
import com.photoeditor.demo.model.event.FilterDownloadBtnClickEvent;
import com.photoeditor.demo.model.event.ReachGPEvent;
import com.photoeditor.demo.model.event.RefreshFilterCategory;
import com.photoeditor.demo.model.event.RefreshStickerEvent;
import com.photoeditor.demo.model.event.SortFilterCategory;
import com.photoeditor.demo.model.event.StickersTurnToFunctionSubscribeEvent;
import com.photoeditor.demo.model.event.StickersTurnToRewardEvent;
import com.photoeditor.demo.model.event.SubscribeSuccessEvent;
import com.photoeditor.demo.model.filter.ImageFilterTools;
import com.photoeditor.demo.model.image.collage.templet.BgBean;
import com.photoeditor.demo.model.image.collage.templet.CollageTemplet;
import com.photoeditor.demo.model.image.collage.templet.ColorBgBean;
import com.photoeditor.demo.model.image.collage.templet.ITempletChangeListener;
import com.photoeditor.demo.model.image.collage.templet.InsideResBgBean;
import com.photoeditor.demo.model.image.collage.templet.MagazineRectf;
import com.photoeditor.demo.model.image.collage.templet.Ratio;
import com.photoeditor.demo.model.image.emoji.IEmojiLoadListener;
import com.photoeditor.demo.model.image.emoji.InsideEmojiResource;
import com.photoeditor.demo.model.image.emoji.LocalStickerData;
import com.photoeditor.demo.model.image.emoji.StickerManager;
import com.photoeditor.demo.model.image.frame.IFrameChangeListener;
import com.photoeditor.demo.model.image.mirror.MirrorTempletConstant;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.sticker.StickerUnlockData;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.HomeOnlineConfig;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.statistics.NotifyStoreUpdateStatisticBean;
import com.photoeditor.demo.statistics.NotifyStoreUpdateStatisticUtil;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.community.ConfirmUploadActivity;
import com.photoeditor.demo.ui.dialog.DialogShow;
import com.photoeditor.demo.ui.dialog.DialogStatistic;
import com.photoeditor.demo.ui.dialog.IAdVideoDialogListener;
import com.photoeditor.demo.ui.dialog.IDialog;
import com.photoeditor.demo.ui.dialog.RateGuide;
import com.photoeditor.demo.ui.dialog.WDialogShow;
import com.photoeditor.demo.ui.fragement.HomeFragment;
import com.photoeditor.demo.ui.widget.BottomInsideBarView;
import com.photoeditor.demo.ui.widget.CustomNumSeekBar;
import com.photoeditor.demo.ui.widget.LoadingView;
import com.photoeditor.demo.ui.widget.RotationImageView;
import com.photoeditor.demo.ui.widget.beauty.BigEyesView;
import com.photoeditor.demo.ui.widget.beauty.BreastView;
import com.photoeditor.demo.ui.widget.beauty.RepairView;
import com.photoeditor.demo.ui.widget.beauty.TailImageView;
import com.photoeditor.demo.ui.widget.blur.LinearBlurTipView;
import com.photoeditor.demo.ui.widget.blur.RadialBlurTipView;
import com.photoeditor.demo.ui.widget.collage.CollageRelativeLayout;
import com.photoeditor.demo.ui.widget.collage.ICollage;
import com.photoeditor.demo.ui.widget.collage.ICollagePathView;
import com.photoeditor.demo.ui.widget.collage.IMagazineTemplateChangeListener;
import com.photoeditor.demo.ui.widget.image.AnimationCropImageView;
import com.photoeditor.demo.ui.widget.image.FilterBarView;
import com.photoeditor.demo.ui.widget.image.brush.BrushView;
import com.photoeditor.demo.ui.widget.image.brush.MopiBrushView;
import com.photoeditor.demo.ui.widget.image.brush.WhitenBrushView;
import com.photoeditor.demo.ui.widget.image.compose.CanvasEditTextView;
import com.photoeditor.demo.ui.widget.image.compose.ICanvasEditListener;
import com.photoeditor.demo.ui.widget.image.compose.IClickEditTextListener;
import com.photoeditor.demo.ui.widget.image.edit.AdjustBarView;
import com.photoeditor.demo.ui.widget.image.edit.BeautyBarView;
import com.photoeditor.demo.ui.widget.image.edit.CropBarView;
import com.photoeditor.demo.ui.widget.image.edit.DoodleBarView;
import com.photoeditor.demo.ui.widget.image.edit.EditOperationView;
import com.photoeditor.demo.ui.widget.image.edit.EmojiBarView;
import com.photoeditor.demo.ui.widget.image.edit.EraserBarView;
import com.photoeditor.demo.ui.widget.image.edit.FilterCallBackListener;
import com.photoeditor.demo.ui.widget.image.edit.FrameBarView;
import com.photoeditor.demo.ui.widget.image.edit.MirrorBarView;
import com.photoeditor.demo.ui.widget.image.edit.MixerBarView;
import com.photoeditor.demo.ui.widget.image.edit.OtherBarView;
import com.photoeditor.demo.ui.widget.image.edit.RotateBarView;
import com.photoeditor.demo.ui.widget.image.edit.StickerSettingTopView;
import com.photoeditor.demo.ui.widget.image.edit.StickerSettingView;
import com.photoeditor.demo.ui.widget.image.edit.TextBarView;
import com.photoeditor.demo.ui.widget.image.edit.TileShiftBarView;
import com.photoeditor.demo.ui.widget.image.emoji.CanvasEditEmojiView;
import com.photoeditor.demo.ui.widget.image.eraser.EraserBgView;
import com.photoeditor.demo.ui.widget.image.eraser.ImageEraserView;
import com.photoeditor.demo.ui.widget.image.frame.PhotoFrameView;
import com.photoeditor.demo.ui.widget.image.hair.Color_view;
import com.photoeditor.demo.ui.widget.image.lip.LipView;
import com.photoeditor.demo.ui.widget.image.magazine.EditMagazineCollageRelativeLayout;
import com.photoeditor.demo.ui.widget.image.magazine.EditMagazineTempletBar;
import com.photoeditor.demo.ui.widget.image.mixer.ImageMixerView;
import com.photoeditor.demo.ui.widget.image.watermark.Watermark;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkLinearLayout;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkManager;
import com.photoeditor.demo.ui.widget.image.watermark.WatermarkSelectView;
import com.photoeditor.demo.ui.widget.stash.edit.StickerView;
import com.photoeditor.demo.util.AsyncTask;
import com.photoeditor.demo.util.AsyncTaskDefaultSerialExecutor;
import com.photoeditor.demo.util.BitmapDecoder;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.CameraDrawable;
import com.photoeditor.demo.util.DateMaskUtil;
import com.photoeditor.demo.util.DialogUtils;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.FileUtil;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.ImageRectUtils;
import com.photoeditor.demo.util.MediaTypeUtil;
import com.photoeditor.demo.util.NetworkUtils;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.folder.FolderHelper;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import static android.view.View.NO_ID;
import static android.view.View.VISIBLE;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.model.preference.SpUtils.FILTERDETAILUNLOCK;
import static com.photoeditor.demo.model.preference.SpUtils.ISFROMBUTTON;
import static com.photoeditor.demo.model.store.module.HomeOnlineConfig.ACTION_FEMALE_ABS;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.REQUEST_CODE_FOR_VIP_ACTIVITY;
import static com.photoeditor.demo.model.subscribe.manager.SVipConstant.VIP_ENTRANCE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_BTN_ADJUST;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_BTN_BEAUTY;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_BTN_BODY;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_BTN_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_BTN_EFFECT;
import static com.photoeditor.demo.statistics.StatisticsConstant.SOURCE_TYPE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_EDITPAGE;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_KEY_FUNCTION_USED;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_BANNER;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_EDIT;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_VALUE_FILTER;
import static com.photoeditor.demo.ui.widget.BottomInsideBarView.TYPE_BUTTON;
import static com.photoeditor.demo.ui.widget.BottomInsideBarView.TYPE_NAME;
import static com.photoeditor.demo.util.DataConstant.IMAGE_DATA;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextViewSize;

//import com.photoeditor.demo.model.image.emoji.LocalStickerData;
//import com.photoeditor.demo.model.image.emoji.StickerManager;

public class EditorImageActivity extends MediaEditBaseActivity implements View.OnClickListener, ICollage, CanvasEditEmojiView.StickerEditListener {

    /**
     * 外面进入时传入参数的key
     */
    private long timeCount;

    private static final String DEGREE = "degree";
    private static final String ENTRANCE = "entrance";
    private String mEntrance;

    /**
     * 外面进入时传入参数的key
     */
    private static final String BEAN = "bean";

    public static final int REQUEST_CODE_SELECT_PIC_2_MIXER = 111;
    public static final int REQUEST_CODE_REPLACE_PIC_2_MIXER = 112;

    /**
     * 总的View
     */
    private RelativeLayout mContentView;

    /**
     * 用于裁剪  View
     */
    private AnimationCropImageView mImageView;

    /**
     * 旋转的 View
     */
    private RotationImageView mRotationImagView;

    /**
     * 美颜时候的遮罩
     */
    private ImageView mImageViewCover;

    /**
     * 美颜时用于动画的View
     */
    private LoadingView mLoadingView;
    private View mLightAnimView;

    /**
     * 涂鸦视图
     */
    private GraffitoView mGraffitoView;

    /**
     * 调整视图  滤镜使用
     */
    private AdjustGPUImageView mAdjustGPUImageView;

    /**
     * 添加emoji视图
     */
    private CanvasEditEmojiView mCanvasEditEmojiView;

    /**
     * 添加文字视图
     */
    private CanvasEditTextView mCanvasEditTextView;

    /**
     * 镜像的视图
     */
    private CollageRelativeLayout mMirrorView;

    private Color_view mHairColorView;

    private BigEyesView mBigEyesView;

    private TailImageView mTailView;

    private LipView mLipView;

    private RepairView mRepairView;

    private BrushView mWhitenTeethView;
    private WhitenBrushView mWhitenBrushView;
    private MopiBrushView mMopiBrushView;

    private BreastView mBreastView;
    private BreastView mButtocksView;


    private RadialBlurTipView mRadialBlurTipView;
    private LinearBlurTipView mLinearBlurTipView;

    private ImageEraserView mImageEraserView;
    private EraserBgView mEraserBgView;

    /**
     * bean
     */
    private BitmapBean mImageBean;

    /**
     * mSrcBitmap是源bitmap  mcacheBitmap是中间Bitmap
     */
    private CameraDrawable mSrcBitmap, mCacheBitmap;

    /**
     * 是否需要保存图片
     */
    private boolean mNeedSave = false;

    /**
     * 是否从第三方软件进来
     */
    private boolean mIsFromOthers = false;

    /**
     * 用于记录当前的选中的Id默认是滤镜
     */
    private int mCurId = R.id.filter;

    /**
     * 记录上一次选择的id
     */
    private int mLastId = -1;

    //水印相关
    private WatermarkManager mWatermarkManager;
    private boolean mWaterMarkIsExist;
    private RelativeLayout mWaterMarkLayout;
    private ImageView mWaterMarkIV;
    private View mWaterMarkBarLayout;

    private ProgressDialog mShareProgressDialog;
    private AlertDialog mExitAlertDialog;


    private ViewGroup mEditOperationViewContainer;
    private ViewGroup mBottomOperationViewContainer;
    private LinearLayout mBottomLayoutOutSide;
    private TextView mExitBt;
    private TextView mSaveBt;

    //private ImageView mOtherNewFlag;
//	private AnimationUtil mAnimationUtil;

    /**
     * 这个是底部用于调节SeekBar的View 或者是显示 名称的View
     */
    private BottomInsideBarView mBottomLayoutInSide;

    private Animation mBottomLayoutBottomOut;
    private Animation mBottomLayoutTopIn;
    private Animation mBottomLayoutBottomIn;
    private Animation mBottomLayoutBottomInUpToDown;
    private Animation mBottomLayoutTopOut;
    private AlphaAnimation mAlphaIn;
    private AlphaAnimation mAlphaOut;

    /**
     * 滤镜部分
     */
    private FilterBarView mFilterView;

    private com.photoeditor.demo.ui.widget.OnSeekBarChangeListener mSeekBarChangeListener;

    private OtherBarView mOtherBarView;
    private AdjustBarView mAdjustBarView;
    private RotateBarView mRotateBarView;
    private CropBarView mCropBarView;
    private DoodleBarView mDoodleBarView;
    /**
     * 添加Emoji相关
     */
    private EmojiBarView mAddEmojiView;

    /**
     * 添加文字
     */
    private TextBarView mAddTextView;

    /**
     * 移轴
     */
    private TileShiftBarView mTileShiftView;

    /**
     * 美颜
     */
    private BeautyBarView mBeautyBarView;

    /**
     * 镜像
     */
    private MirrorBarView mMirrorBarView;

    private EraserBarView mEraserBarView;

    /**
     * 合并edit的二级目录
     */
    private EditOperationView mEditOperationBar;

    /**
     * PIP
     */
//    private LinearLayout mPipProcessLayout;
//    private PipProcessView mPipProcessView;

    /**
     * 这个是SEEKBAR上面的那个调节圆
     */
    private TextView mProgressTv;
    private View mProgressLayout;

    /**
     * 顶部标题名字
     */
    private TextView mTvTitle;

    private View mBottomTab;
    private View mImageContent;

    /**
     * 是否需要分享
     */
    private boolean mIsNeedShare = false;

    private boolean mIsNeedStartPreview = false;

    private boolean mIsNeedPublish = false;

    /**
     * 是否需要直接跳转EmojiBar
     */
    private boolean mIsNeedGoToEmojiBar = false;
    private boolean mIsNeedGoToBeauty = false;
    /**
     * 是否需要直接跳转到beautyBar的某个具体功能
     */
    private boolean mIsNeedGoToBeautyOrBodyFuntion = false;

    private String mCheckedStickerPkgName;
    private String mGifTitle;
    private int mGifAutoScrollPosition = -1;
    private int mStickerAutoScrollPosition = -1;

    private boolean mNeedToApplyFilter = false;
    private String mCheckedFilterCategoryId = null;
    private String mCheckedFilterPkgName = null;

    public StickerManager mStickerManager;
    private PhotoFrameView mFrameView;
    private FrameBarView mFrameBarView;
    //统计保存杂志时所用的模板位置
    private int mRecoredCurrentMagazinePosition;
    //	private Bitmap mFrameBitmap;
    private int trueW, trueH;

    private AsyncTask mSaveTask;

    private StickerSettingView mStickerSettingView;
    private StickerSettingTopView mStickerSettingTopView;

    private ImageView mCoverImageView;
    private View mCoverLayout;

    private boolean mShowWatermark;

    private UseEffectInfo mUseEffectInfo;
    private String mOriginalFilePath;

    //使用过的滤镜和贴纸， 贴纸是包名， 滤镜是categoryname
    private List<String> mUsedStickerAndFilter;

    private boolean mOnSaveOperation; // 是否由保存操作而关闭页面

    private List<String> mUnlockFilter = new CopyOnWriteArrayList<>(); //看激励视频解锁的滤镜，当次有效

    /**
     * 滤镜效果回调listener
     */
    private FilterCallBackListener mFilterCallBackListener = new FilterCallBackListener() {

        @Override
        public Bitmap getSrcBitmap() {
            return mSrcBitmap != null ? mSrcBitmap.getBitmap() : null;
        }

        @Override
        public void applyed() {
            if (mCacheBitmap != null && mCacheBitmap != mSrcBitmap) {
                if (mSrcBitmap != null) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = mCacheBitmap;
                mNeedSave = true;
                mCacheBitmap = null;
            }
        }

        @Override
        public void proccess(Bitmap bitmap) {
            if (bitmap != null) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                if (mCacheBitmap != null) {
//                    mCacheBitmap.recycle();
                }
                mCacheBitmap = cd;
            }
        }

        @Override
        public void cancel() {
            if (mSrcBitmap == null) {
                return;
            }
            mImageView.setImageDrawable(mSrcBitmap);
            if (mCacheBitmap != null) {
//                mCacheBitmap.recycle();
            }
            mCacheBitmap = null;

        }
    };

    private AlertDialog mShareFBTipDialog;
//	private AlertDialog mShareToFBDialog;
//	private ImageView mShareImageView;

    private boolean mHasDateMark;
    private boolean mHasUserModify = false;

    private int tabId;

    private ITempletChangeListener mTempletChangeListener = new ITempletChangeListener() {
        @Override
        public void onTempletChange(CollageTemplet templet) {
            mMirrorView.setTemplet(templet);
        }

        @Override
        public void onTypeChange(Ratio.RATIO type) {
            mMirrorView.setType(type);
        }

        @Override
        public void onBackgroundChange(BgBean bean) {
            if (bean instanceof ColorBgBean) {
                ColorBgBean colorBgBean = (ColorBgBean) bean;
                mMirrorView.setBgDrawable(colorBgBean.get());
            } else if (bean instanceof InsideResBgBean) {
                InsideResBgBean insideResBgBean = (InsideResBgBean) bean;
                mMirrorView.setBgResource(insideResBgBean.get());
            }
        }
    };
    private IFrameChangeListener mFrameChangListener = new IFrameChangeListener() {

        @Override
        public void frameChange(Drawable drawable) {

            mFrameDrawable = ImageHelper.zoomDrawable(drawable, mFrameView.getWidth(), mFrameView.getHeight());
            //消除drawable引用
            drawable.setCallback(null);
            mFrameView.setBackgroundDrawable(mFrameDrawable);
        }
    };
    private IMagazineTemplateChangeListener mIMagazineTempletChangeListener = new IMagazineTemplateChangeListener() {
        @Override
        public void magazineTemplateChange(Object itemBitp, int position, float ratio, MagazineBean targetBean) {
            if (itemBitp == null || !(itemBitp instanceof Bitmap)) {
                return;
            }
            mRecoredCurrentMagazinePosition = position;
            mMagazineView.setRatioAnTempletAndBg(ratio, position, mMagazineRectfs.get(position), (Bitmap) itemBitp);
        }

        @Override
        public void beforeTemplateChange() {

        }

        @Override
        public void repeatClickTemplate(int position) {
        }
    };

    //换发色新增
    private RelativeLayout mGuideLayout;
    private Bitmap mRealBitmap;

    private Handler mHandler;
    private Drawable mFrameDrawable;
    private EditMagazineCollageRelativeLayout mMagazineView;
    private EditMagazineTempletBar mMagazineTempletBar;
    private ArrayList<MagazineRectf> mMagazineRectfs;
    private boolean isFirstCome = true;
    private ProgressBar mLoadingProgress;
    private ArrayList<MagazineBean> mMagazineDatas;
    private boolean isFirstIntoFrame = true;
    private ProgressDialog mSaveTaskProgressDialog;

    private View mTopView;
    //	private MagazineManager mMagazineManager;

    private Bitmap mStickerViewBg;
    private Bitmap mBackgroundBitmap;

    private ImageView mIvBackground;

    private boolean mFirstLoadStickerData = true;
    private AsyncTask mGetBitmapTask;
    private MixerBarView mMixerBarView;
    private ImageMixerView mImageMixerView;

    //从主页btn点击进来
    private String mMainButtonEntrance;
    private boolean mStickerUsed;
    private boolean mFilterUsed;
    private boolean mCropUsed;
    private boolean mAdjustUsed;
    private boolean mTextUsed;
    private boolean mDoodleUsed;
    private boolean mEraserUsed;
    private boolean mMixerUsed;
    private boolean mMirrorUsed;
    private boolean mBlurUsed;
    private boolean mRotateUsed;
    private boolean mBeautyUsed;
    private boolean hasShowWatermarkSVip = false;
    private boolean mIsFirstTimeInBeauty = true;
    private boolean mIsEmojiPanelShow;

    /**
     * 是否进入艺术滤镜
     */
    private boolean mIsEnterArtistFilter = false;
    private boolean mCheck2SaveWatermark;
    private boolean mCheck2SaveDoodle;
    private boolean mCheck2SaveFilter;

    private EditCompleteAdProvider mAdProvider;
    private MainReturnAdProvider mExitAdProvider;
    private Handler mFirstRefreshEmojiHandler;

    /**
     * 启动ImageEditActivity
     *
     * @param context
     * @param image_uri
     * @param degree
     * @param action
     */
    public static void startImageEditActivity(Activity context, Uri image_uri, int degree, String action, int requestCode, String mainButtonEntrance, String entrance) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(action);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ENTRANCE, entrance);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动ImageEditActivity并选中edit界面艺术滤镜
     *
     * @param context
     * @param image_uri
     * @param degree
     * @param action
     */
    public static void startImageEditActivityForArtist(Activity context, Uri image_uri, int degree, String action, int requestCode, String mainButtonEntrance) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(action);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ENTRANCE, "main_page_editor_banner");
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        intent.putExtra(HomeFragment.EXTRA_IS_ARTIST, true);
        context.startActivityForResult(intent, requestCode);
    }

    public static void startImageEditActivity(Activity context, Uri image_uri, int degree, String action, int requestCode, int topicId) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(action);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, topicId);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动ImageEditActivity
     *
     * @param context
     * @param image_uri
     * @param degree
     * @param requestCode
     */
    public static void startImageEditActivity(Activity context, Uri image_uri, int degree, int requestCode) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        context.startActivityForResult(intent, requestCode);
    }

    /**
     * 启动ImageEditActivity
     */
    public static void startImageEditActivityAndShare(Activity context, Uri image_uri, int degree, boolean isPrivate) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_IMAGE_EDIT_AND_SHARE);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        context.startActivity(intent);
    }

    public static void startImageEditActivityAndPublish(Activity context, Uri image_uri, int degree, boolean isPrivate, int topicId) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_IMAGE_EDIT_AND_PUBLISH);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, topicId);
        context.startActivity(intent);
    }

    public static void startImageEditActivityGoToAddEmoji(Activity context, Uri image_uri, int degree, boolean isPrivate, String pkgName, String gifTitle, int autoAddPosition) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
        intent.putExtra(ActionConstant.Extras.EXTRA_GIF_TITLE, gifTitle);
        intent.putExtra(ActionConstant.Extras.EXTRA_AUTO_SCROLL_POSITION, autoAddPosition);
        context.startActivity(intent);
    }

    public static void startImageEditActivityToApplyFilter(Activity context, Uri image_uri, String categoryId, String pkgName, int degree, String entrance) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_APPLY_FILTER);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ENTRANCE, entrance);
        intent.setData(image_uri);
        intent.putExtra(ActionConstant.Extras.EXTRA_CATEGORY_ID, categoryId);
        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
        context.startActivity(intent);
    }


    public static void startImageEditActivityGoToBeauty(Activity context, Uri image_uri, int degree, String mainButtonEntrance) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_EDIT);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        context.startActivity(intent);
    }

    /**
     * 跳转到BeautyOrBody的具体功能
     *
     * @param type 功能类型
     */
    public static void startImageEditActivityGoToBeautyOrBodyFuntion(Activity context, Uri image_uri, int degree, String type, String mainButtonEntrance) {
        Intent intent = new Intent(context, EditorImageActivity.class);
        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT);
        intent.setData(image_uri);
        intent.putExtra(DEGREE, degree);
        intent.putExtra(ActionConstant.Extras.EXTRA_BEAUTY_FUNTION_TYPE, type);
        intent.putExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE, mainButtonEntrance);
        context.startActivity(intent);
    }

    /**
     * 跑着个执行 onnewIntent
     */
//    public static void startImageEditActivityGoToAddEmojiNewIntent(Activity context, String pkgName) {
//        Intent intent = new Intent(context, ImageEditActivity.class);
//        intent.setAction(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT);
//        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
//                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        intent.putExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME, pkgName);
//        context.startActivity(intent);
//    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpUtils.obtain().getBoolean(SpConstant.FRIST_ENTER_STICKERS,true);
        timeCount = System.currentTimeMillis();
        SPDataManager.setArtistEnable(true);
        ImageLoader.clearMemoryCache();
        mWatermarkManager = new WatermarkManager(this);
        mWatermarkManager.setWatermarkUpdateListener(new WatermarkManager.OnWatermarkUpdateListener() {
            @Override
            public void onWatermarkUpdate() {
                refreshWaterMark();
                mWaterMarkIV.setImageBitmap(mWatermarkManager.getWatermarkBitmap(mWatermarkManager.getCurrentWatermark()));
            }
        });
        Intent intent = getIntent();
        if (intent == null) {
            finish();
        } else {
            Uri uri = null;
            final String action = intent.getAction();
            mIsEnterArtistFilter = intent.getBooleanExtra(HomeFragment.EXTRA_IS_ARTIST, false);
            mEntrance = intent.getStringExtra(ENTRANCE);
            if (action != null && Intent.ACTION_SEND.equals(action)) {
                Bundle extras = intent.getExtras();
                if (extras != null && extras.containsKey(Intent.EXTRA_STREAM)) {
                    uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                }
            }

            if (uri == null) {
                uri = intent.getData();
            }
            if (uri == null) {
                finish();
                return;
            }
            if (action != null) {
                if (action.equals(Intent.ACTION_SEND)) {
                    mIsFromOthers = true;
                } else if (action.equals(Intent.ACTION_EDIT)) {
                    mIsFromOthers = true;
                } else if (action.equals(ActionConstant.Actions.ACTION_IMAGE_EDIT_AND_SHARE)) {
                    mIsNeedShare = true;
                } else if (action.equals(ActionConstant.Actions.ACTION_IMAGE_EDIT_AND_PUBLISH)) {
                    mIsNeedPublish = true;
                } else if (action.equals(ActionConstant.Actions.ACTION_PICK_TO_EDIT)) {
                    mIsNeedStartPreview = true;
                } else if (action.equals(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT)) {
//                    mIsNeedGoToBeauty = true;
                    mIsNeedGoToEmojiBar = true;
                    mCheckedStickerPkgName = intent.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
                    mGifTitle = intent.getStringExtra(ActionConstant.Extras.EXTRA_GIF_TITLE);
                    if (!TextUtils.isEmpty(mGifTitle)) {
                        mGifAutoScrollPosition = intent.getIntExtra(ActionConstant.Extras.EXTRA_AUTO_SCROLL_POSITION, -1);
                    } else {
                        mStickerAutoScrollPosition = intent.getIntExtra(ActionConstant.Extras.EXTRA_AUTO_SCROLL_POSITION, -1);
                    }
                } else if (action.equals(ActionConstant.Actions.ACTION_PICK_TO_APPLY_FILTER)) {
//                    mIsNeedGoToBeauty = true;
                    mNeedToApplyFilter = true;
                    mCheckedFilterPkgName = intent.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
                    mCheckedFilterCategoryId = intent.getStringExtra(ActionConstant.Extras.EXTRA_CATEGORY_ID);
                } else if (action.equals(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_EDIT)) {
                    mIsNeedGoToBeauty = true;
                } else if (action.equals(ActionConstant.Actions.ACTION_PICK_TO_BEAUTY_OR_BODY_FUNTION_EDIT)) {
                    mIsNeedGoToBeauty = true;
                    mIsNeedGoToBeautyOrBodyFuntion = true;
                }
            }

            try {
                if (mIsFromOthers) {//这里对Uri做判断  处理不同的Uri
                    mImageBean = ImageHelper.getInterBitmapBeanFormUri(this, uri);
                } else {
                    mImageBean = ImageHelper.getInterBitmapBeanFormUri(this, uri);
                    if (mImageBean != null) {
                        mImageBean.mDegree = intent.getIntExtra(DEGREE, 0);
                    }
                }

                if (mImageBean == null || mImageBean.mType == MediaTypeUtil.TYPE_VIDEO) {
                    finish();
                } else {
                    mMainButtonEntrance = intent.getStringExtra(HomeFragment.EXTRA_MAIN_BTN_ENTRANCE);
                    String path = mImageBean.mPath;
                    mOriginalFilePath = path;
                    mHasDateMark = DateMaskUtil.hasDateMark(path);
                    setContentView(R.layout.activity_image_editor);
                    mFirstRefreshEmojiHandler = new FirstRefreshEmojiHandler();
                    inflateView();
                    EventBus.getDefault().register(this);
                    new AsyncTask<Void, Void, Void>() {

                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            getLoadingView().startLoading();

                        }

                        @Override
                        protected Void doInBackground(Void... params) {
                            mSrcBitmap = new CameraDrawable(getResources(), ImageHelper.UriToBitmap(mImageBean));
                            createBackgroundBitmap(mSrcBitmap.getBitmap());
                            return null;
                        }

                        protected void onPostExecute(Void result) {
                            super.onPostExecute(result);
                            getLoadingView().stopLoading();
                            if (mSrcBitmap == null || mSrcBitmap.getBitmap() == null || mImageView == null) {
                                Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_image_load_failed_tips), Toast.LENGTH_SHORT).show();
                                finish();
                                return;
                            }
                            if (EditorImageActivity.this.isDestroyed()) {
                                return;
                            }
//                            mAdjustGPUImageView.setScaleType(GPUImage.ScaleType.CENTER_INSIDE);
                            initGPUImageView();
                            mAdjustGPUImageView.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (EditorImageActivity.this.isDestroyed()) {
                                        return;
                                    }
                                    mImageView.setImageDrawable(mSrcBitmap);
                                    mAdjustGPUImageView.setImage(mSrcBitmap.getBitmap());
                                    mSrcBitmapCopy = mSrcBitmap.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
                                    mCoverImageView.setImageBitmap(mSrcBitmap.getBitmap());
                                    initialize();
                                    ThreadPool.runUITask(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (EditorImageActivity.this.isDestroyed()) {
                                                return;
                                            }
                                            {
                                                if (mImageContent != null) {
                                                    mImageContent.setVisibility(View.INVISIBLE);
                                                    mCoverImageView.setVisibility(View.VISIBLE);
                                                    //根据当前显示图片，提取出模糊背景
                                                    mIvBackground.setImageBitmap(mBackgroundBitmap);
                                                }
                                                //如果是从主页edit点进来，增加统计
                                                if (TextUtils.equals(action, ActionConstant.Actions.ACTION_PICK_TO_EDIT)) {
                                                    mOtherBarView.scrollToStart();
                                                    mOtherBarView.getItemWidth();
                                                    mOtherBarView.getBarItemCount();
                                                    mOtherBarView.statisticItemShow(mOtherBarView.getHorizontalBarScrollX());
                                                }

                                                // TODO: 2019/4/12 选中艺术滤镜
                                                if (mIsEnterArtistFilter) {
                                                    try {
                                                        onOperationClick(R.id.filter);
                                                        ThreadPool.runUITask(new Runnable() {
                                                            @Override
                                                            public void run() {
                                                                mFilterView.onChooseArtist();
                                                            }
                                                        }, 100);
                                                    } catch (Exception e) {
                                                        e.printStackTrace();
                                                    }
                                                }

                                                if (mIsNeedGoToEmojiBar /*&& !TextUtils.isEmpty(mCheckedStickerPkgName)*/){
                                                    onOperationClick(R.id.sticker);//初始化addEmoji
                                                } else
                                                if (mNeedToApplyFilter && mCheckedFilterCategoryId != null && mCheckedFilterPkgName != null) {
                                                    //isFirstApplyAndNeedBuy=true;
                                                    RefreshFilterCategory refreshFilterCategory = new RefreshFilterCategory();
                                                    refreshFilterCategory.showCategoryId = mCheckedFilterCategoryId;
                                                    refreshFilterCategory.selFilterPkgName = mCheckedFilterPkgName;
                                                    EventBus.getDefault().post(refreshFilterCategory);
                                                }
                                            }
                                            // 直接进入beauty模式，不显示水印
                                            if (mNeedToApplyFilter || mIsNeedGoToEmojiBar || mIsEnterArtistFilter) {
                                                setWaterMarkVisible(false);
                                            } else {
                                                setWaterMarkVisible(true);
                                            }

                                        }
                                    }, 120);
                                }
                            });
                        }
                    }.execute();

                    if (!TextUtils.isEmpty(mMainButtonEntrance)) {
                        switch (mMainButtonEntrance) {
                            case MAIN_BTN_BODY:
                                findViewById(R.id.edit).setVisibility(View.GONE);
                                break;
                            case MAIN_BTN_BEAUTY:
                                findViewById(R.id.edit).setVisibility(View.GONE);
                                break;
                            case MAIN_BTN_EFFECT:
                                mOtherBarView.setCurrentType(OtherBarView.BarType.TYPE_ID_EFFECT);
                                break;
                            case MAIN_BTN_EDIT:
                                mOtherBarView.setCurrentType(OtherBarView.BarType.TYPE_ID_EDIT);
                                break;
                            case MAIN_BTN_ADJUST:
                                mOtherBarView.setCurrentType(OtherBarView.BarType.TYPE_ID_ADJUST);
                                break;
                            default:
                                break;
                        }
                    }
                }
            } catch (Throwable e) {
                if (TestUser.isTestUser()) {
                    throw e;
                } else {
                    e.printStackTrace();
                }
            }
        }

        mUseEffectInfo = new UseEffectInfo();
        mUsedStickerAndFilter = new ArrayList<>();

        if (!AppVipManager.isVip()) {
            mAdProvider = new EditCompleteAdProvider(this);
            mAdProvider.loadAd();
            mExitAdProvider = new MainReturnAdProvider(this, StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_EDIT);
            mExitAdProvider.loadAd();
        }
        EditCompleteAdProvider.statistics("in", "where", "image");

        long interval = System.currentTimeMillis() - timeCount;
        String stayTime;
        if (interval < 30 * 1000) {
            stayTime = "(0,30)";
        } else if (interval < 60 * 1000) {
            stayTime = "(30,60)";
        } else if (interval < 120 * 1000) {
            stayTime = "(60,120)";
        } else {
            stayTime = "(120,)";
        }

        if (TextUtils.equals(mEntrance, "main_page_editor_filter")) {
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SHOW,
                    StatisticsConstant.KEY_EDIT_PAGE_ENTR, STATISTIC_VALUE_FILTER,
                    StatisticsConstant.KEY_STAY_TIME, stayTime);
        } else if (TextUtils.equals(mEntrance, "main_page_editor_floating")) {
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SHOW,
                    StatisticsConstant.KEY_EDIT_PAGE_ENTR, STATISTIC_VALUE_EDIT,
                    StatisticsConstant.KEY_STAY_TIME, stayTime);
        } else if (TextUtils.equals(mEntrance, "main_page_editor_banner")) {
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SHOW,
                    StatisticsConstant.KEY_EDIT_PAGE_ENTR, STATISTIC_VALUE_BANNER,
                    StatisticsConstant.KEY_STAY_TIME, stayTime);
        }

        System.gc();

    }

    /**
     * 根据外部传进来的类型判断选中body还是beauty
     */
//    private void selectBeautyOrBodyFromType(String type) {
//        switch (type) {
//            case HomeOnlineConfig.ACTION_BOBJOB:
//            case HomeOnlineConfig.ACTION_BUTTOCK:
//            case ACTION_FEMALE_ABS:
//            case HomeOnlineConfig.ACTION_PECS:
//            case HomeOnlineConfig.ACTION_MALE_ABS:
//            case HomeOnlineConfig.ACTION_BICEP:
//            case HomeOnlineConfig.ACTION_TALLER:
//                onOperationClick(R.id.body);
//                break;
//            default:
//                onOperationClick(R.id.beauty);
//                break;
//        }
//    }
    private void selectDefaultBottomTabByAction(String type) {
        switch (type) {
            case HomeOnlineConfig.ACTION_BOBJOB:
            case HomeOnlineConfig.ACTION_BUTTOCK:
            case ACTION_FEMALE_ABS:
            case HomeOnlineConfig.ACTION_PECS:
            case HomeOnlineConfig.ACTION_MALE_ABS:
            case HomeOnlineConfig.ACTION_BICEP:
            case HomeOnlineConfig.ACTION_TALLER:

                getBeautyBarView().setVisibility(VISIBLE);
                getBeautyBarView().chageStateType(BeautyBarView.TYPE_BODY);
                break;
            case HomeOnlineConfig.ACTION_RETOUCH:
            case HomeOnlineConfig.ACTION_HEALING:
            case HomeOnlineConfig.ACTION_SMOOTH:
            case HomeOnlineConfig.ACTION_HAIR_COLOR:
            case HomeOnlineConfig.ACTION_EYETUNER:
            case HomeOnlineConfig.ACTION_LIPSTICK:
            case HomeOnlineConfig.ACTION_EYE_SHADOW:
            case HomeOnlineConfig.ACTION_EYE_LASHES:
            case HomeOnlineConfig.ACTION_CONTACTS_LENSES:

                getBeautyBarView().setVisibility(VISIBLE);
                getBeautyBarView().chageStateType(BeautyBarView.TYPE_BEAUTY);
                break;
            default:
                break;
        }
    }

    /**
     * 初始化一些View
     */
    private void inflateView() {
        mCurId = View.NO_ID;

        mCoverLayout = findViewById(R.id.layout_cover);
        mCoverImageView = (ImageView) findViewById(R.id.iv_cover);
        mIvBackground = (ImageView) findViewById(R.id.iv_background);
        mTopView = findViewById(R.id.rl_top_layout);
        mContentView = (RelativeLayout) findViewById(R.id.content);
        mBottomTab = findViewById(R.id.bottom_tab);
        mImageContent = findViewById(R.id.image_content);
        mEditOperationViewContainer = (ViewGroup) findViewById(R.id.edit_operation_view);
        mBottomOperationViewContainer = (ViewGroup) findViewById(R.id.bottom_operation_view);
        if (mIsNeedGoToBeauty) {
            translateY = getResources().getDimensionPixelSize(R.dimen.image_eidt_top_height);
            translateY = translateY / 2;
            RelativeLayout.LayoutParams coverLp = (RelativeLayout.LayoutParams) mCoverLayout.getLayoutParams();
            RelativeLayout.LayoutParams contentLp = (RelativeLayout.LayoutParams) mImageContent.getLayoutParams();
            coverLp.bottomMargin = getResources().getDimensionPixelSize(R.dimen.image_edit_margin_bottom_in_beauty);
            contentLp.topMargin += translateY;
            contentLp.bottomMargin += translateY;

            //findViewById(R.id.edit_operation_view).setPadding(0, 0, 0, getResources().getDimensionPixelOffset(R.dimen.image_eidt_bottom_height));

        } else {
            translateY = ComponentContext.getContext().getResources().getDimension(R.dimen.image_eidt_top_height);
        }
        //初始化
        mImageView = (AnimationCropImageView) findViewById(R.id.imageview);
        mRotationImagView = (RotationImageView) findViewById(R.id.rotate_view);
        mImageViewCover = (ImageView) findViewById(R.id.gpuimageview_cover);
        mLightAnimView = findViewById(R.id.beauty_anim_view);
        mGraffitoView = (GraffitoView) findViewById(R.id.graffitoview);
        mCanvasEditTextView = (CanvasEditTextView) findViewById(R.id.canvas_edittext_view);
        mCanvasEditTextView.setListener(new ICanvasEditListener() {
            @Override
            public void onNeedSaveChangedTo(boolean value) {
                setConfirmEnable(value);
            }

            @Override
            public void onTouchMove(float x) {

            }

            @Override
            public void onTouchDown(float x) {

            }

            @Override
            public void onTouchUp(float x) {

            }

            @Override
            public void onSelected(Object... params) {
                if (mAddTextView != null) {
                    if (params.length == 0) {
                        mAddTextView.reset();
                    } else if (params.length == 3) {
                        mAddTextView.setParams((int) params[0], (int) params[1], (String) params[2]);
                    }
                }
            }

            @Override
            public void onDelete(ContainerBean bean) {
                if (mAddTextView != null) {
                    mAddTextView.reset();
                }
            }

            @Override
            public void onAdd(ContainerBean bean) {

            }
        });
        mCanvasEditTextView.setOnEditTextClickListener(new IClickEditTextListener() {
            @Override
            public void onclick(TextBean bean) {
                if (mAddTextView != null) {
                    if (!bean.isNeedSave()) {
                        mAddTextView.showEditText("");
                    } else {
                        mAddTextView.showEditText(bean.getString());
                    }
                }
            }
        });
        mCanvasEditEmojiView = (CanvasEditEmojiView) findViewById(R.id.canvas_editemoji_view);
        mCanvasEditEmojiView.setStickerEditListener(this);
        mCanvasEditEmojiView.setListener(new ICanvasEditListener() {
            @Override
            public void onNeedSaveChangedTo(boolean value) {
                setConfirmEnable(value);
            }

            @Override
            public void onTouchMove(float x) {

            }

            @Override
            public void onTouchDown(float x) {
                if(mAddEmojiView != null) {
                    mAddEmojiView.setEmojiPanelVisible(false, true);
                    mAddEmojiView.restore(false);
                }
            }

            @Override
            public void onTouchUp(float x) {

            }

            @Override
            public void onSelected(Object... params) {

            }

            @Override
            public void onDelete(ContainerBean bean) {
                if (mIsNeedGoToBeauty && mBottomLayoutInSide.getVisibility() == View.VISIBLE) {
                    if (mCanvasEditEmojiView.getBeans().size() == 0) {
                        mTopView.startAnimation(getTopIn());
                        mTopView.setVisibility(View.VISIBLE);
                        hideOperationBarWithAnim(mCurId);
                        doImageContentAnim(false);
                    }
                }
            }

            @Override
            public void onAdd(ContainerBean bean) {
                if (mIsNeedGoToBeauty && mBottomLayoutInSide.getVisibility() != View.VISIBLE) {
                    mTopView.startAnimation(getTopOut());
                    mTopView.setVisibility(View.GONE);
                    showOperationBarWithAnim(mCurId);
                    doImageContentAnim(true);
                }
            }
        });
        mAdjustGPUImageView = (AdjustGPUImageView) findViewById(R.id.gpuimageview);
        mAdjustGPUImageView.setBackgroundColor(0x00000000);
        mMirrorView = (CollageRelativeLayout) findViewById(R.id.mirrorview);
        mMirrorView.setFromMirror(true);
        mHairColorView = (Color_view) findViewById(R.id.paintview);
        mBigEyesView = (BigEyesView) findViewById(R.id.big_eyes_view);
        mTailView = (TailImageView) findViewById(R.id.tail_view);
        mLipView = (LipView) findViewById(R.id.lipview);
        mRepairView = (RepairView) findViewById(R.id.repair_view);
        mWhitenTeethView = (BrushView) findViewById(R.id.whiten_teeth_view);
        mMopiBrushView = (MopiBrushView) findViewById(R.id.mopi_view);
        mWhitenBrushView = (WhitenBrushView) findViewById(R.id.whiten_view);
        mFrameView = (PhotoFrameView) findViewById(R.id.frameview);
        mMagazineView = (EditMagazineCollageRelativeLayout) findViewById(R.id.magazineview);
        mGuideLayout = (RelativeLayout) findViewById(R.id.guide_layout);
        mBreastView = findViewById(R.id.breast_view);
        mBreastView.setBreastViewListener(mBreastViewListener);
        mButtocksView = findViewById(R.id.buttocks_view);
        mButtocksView.setBreastViewListener(mBreastViewListener);
        if (SPDataManager.getEditShowHairColorTip()) {
            mGuideLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismissGuideView();
                }
            });
        }


        /**
         * 默认先显示滤镜
         */
        mFilterView = (FilterBarView) findViewById(R.id.filter_bar);
        mFilterView.hidevignetteTiltshiftButton();
        mFilterView.setSourceType(SOURCE_TYPE_EDIT);

        mBottomLayoutOutSide = (LinearLayout) findViewById(R.id.bottom_layout_outside);
        mExitBt = (TextView) findViewById(R.id.exit);
        mSaveBt = (TextView) findViewById(R.id.save);

        mOtherBarView = (OtherBarView) findViewById(R.id.other_layout);
        mOtherBarView.setOnClickListener(this);

        //mOtherNewFlag = (ImageView)findViewById(R.id.other_new_flag);

        mProgressLayout = findViewById(R.id.progress_layout);
        mProgressTv = (TextView) findViewById(R.id.progress_tv);
        mTvTitle = findViewById(R.id.edit_title);
        FontUtil.setCustomFontBold((TextView) findViewById(R.id.edit_title));
        FontUtil.setCustomFont(mProgressTv, mExitBt, mSaveBt);
        mLoadingProgress = (ProgressBar) findViewById(R.id.loading_progress);
        mWaterMarkIsExist = !mHasDateMark && mWatermarkManager.isWatermarkExist();

        mImageEraserView = findViewById(R.id.eraser_view);
        mEraserBgView = findViewById(R.id.eraser_bg_view);
        mImageEraserView.setEraserBgView(mEraserBgView);

        mImageMixerView = findViewById(R.id.mixer_view);

//        mPipProcessLayout = (LinearLayout) findViewById(R.id.pip_process_layout);

        LocalStickerData.from = InsideEmojiResource.FROM_EDIT;
        mStickerManager = new StickerManager(this);
        //初始化Emoji资源 需要异步
        mStickerManager.setEmojiLoadListener(new IEmojiLoadListener() {
            @Override
            public void onLoadEmojiFinish() {//EMOJI加载完成的回调 异步的
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        DLog.d("fLog", "mAddEmojiView != null?" + (mAddEmojiView != null));
                        if (mAddEmojiView != null) {
                            if(SpUtils.obtain().getBoolean(SpConstant.FRIST_ENTER_STICKERS,false)){
                                mAddEmojiView.init();
                            }
                            SpUtils.obtain().save(SpConstant.FRIST_ENTER_STICKERS,false);
                            LocalStickerData.from = InsideEmojiResource.FROM_EDIT;
                            mAddEmojiView.dismissWaitingDailog();
                            if(!mFirstLoadStickerData) {
                                mAddEmojiView.setSelectPakName(getStickerPkgName());
                                mAddEmojiView.setGifTitle(getGifTitle());
                                mAddEmojiView.setStickerAutoScrollPosition(mStickerAutoScrollPosition);
                                mAddEmojiView.setGifAutoScrollPosition(mGifAutoScrollPosition);
                                mStickerAutoScrollPosition = -1;
                                mGifAutoScrollPosition = -1;
                                setCheckedStickerPkgNameNull();
                                setGifTitleNull();
                            }
                            mAddEmojiView.reloadData();
                        } else {
                            mFirstRefreshEmojiHandler.sendEmptyMessage(1);
                        }
                        if(mFirstLoadStickerData) {
                            mFirstLoadStickerData = false;
                        }
                    }
                }, 1000);
            }
        });

        initWaterMark();

        if (!mWaterMarkIsExist && !AppVipManager.isAdVip()) {
            mWaterMarkIsExist = true;
            Watermark watermark = mWatermarkManager.getAvailableWatermarks().get(1);
            mWatermarkManager.setCurrentWatermark(watermark);
            Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
            if (bitmap != null) {
                mWaterMarkIV.setImageBitmap(bitmap);
            }
            refreshWaterMark();
        }

        setSaveBtEnable(mWaterMarkIsExist || AppVipManager.isVip());

        mHandler = new Handler();
//        mMagazineRectfs = MagazineTempletConstant.magazineTotalTemplet.get(1);

        initView();

//        if (mIsNeedGoToBeauty) {
//            mTopView.setVisibility(View.VISIBLE);
//            if (mBottomLayoutInSide == null) {
//                initBottomLayoutInSide();
//            }
//            mTvTitle.setVisibility(View.INVISIBLE);
//            mBottomLayoutInSide.setVisibility(View.GONE);
//            mBottomLayoutOutSide.setVisibility(View.GONE);
//            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mBottomLayoutBeauty.getLayoutParams();
//            layoutParams.bottomMargin = DeviceUtils.dip2px(-5);
//            setWaterMarkVisible(false);
//            if (!mIsNeedGoToBeautyOrBodyFuntion && !mIsNeedGoToEmojiBar && !mNeedToApplyFilter){
//                //点击主功能beauty按钮进入的情况，设置默认显示的底部按钮
//                switch (mMainButtonEntrance) {
//                    case MAIN_BTN_BEAUTY:
//                        mBottomLayoutBeauty.changeTabState(R.id.beauty);
//                        getBeautyBarView();
//                        break;
//                    case MAIN_BTN_BODY:
//                        mBottomLayoutBeauty.changeTabState(R.id.body);
//                        getBeautyBarView();
//                        break;
//                    case MAIN_BTN_EDIT:
//                        mBottomLayoutBeauty.changeTabState(R.id.edit);
//                        getEditOperationBar();
//                        break;
//                }
//            } else if (mIsNeedGoToBeautyOrBodyFuntion && !mIsNeedGoToEmojiBar && !mNeedToApplyFilter) {
//                //通过hot feature或banner进行跳转的情况，设置默认显示的底部按钮
//                String type = getIntent().getStringExtra(ActionConstant.Extras.EXTRA_BEAUTY_FUNTION_TYPE);
//                if (!TextUtils.isEmpty(type)) {
//                    selectDefaultBottomTabByAction(type);
//                }
//            }
//        }
        mMirrorView.setIsSingeleBitmapMode(true);

//        String entrance;
//        if (mNeedToApplyFilter || mIsNeedGoToEmojiBar) {
//            entrance = StatisticsConstant.MAIN_BTN_EFFECT;
//        } else if (TextUtils.equals(mMainButtonEntrance, MAIN_BTN_EDIT) && !mIsEnterArtistFilter) {
//            entrance = StatisticsConstant.EDIT_PAGE_ENTR_VALUE_EDIT;
//        } else {
//            entrance = StatisticsConstant.EDIT_PAGE_ENTR_VALUE_OTHER;
//        }
//        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SHOW,
//                StatisticsConstant.KEY_EDIT_PAGE_ENTR, entrance);
    }

    private BreastView.BreastViewListener mBreastViewListener = new BreastView.BreastViewListener() {
        @Override
        public void showLoading() {
            if (mSaveTaskProgressDialog == null) {
                mSaveTaskProgressDialog = DialogUtils.showCoverProgressDialog(EditorImageActivity.this);
            } else {
                mSaveTaskProgressDialog.show();
            }
            getLoadingView().startLoading();
        }

        @Override
        public void hideLoading() {
            getLoadingView().stopLoading();
            if (mSaveTaskProgressDialog != null && !isFinishing()) {
                mSaveTaskProgressDialog.dismiss();
            }
        }

        @Override
        public void resetSeekBar() {
            getBeautyBarView().resetBreastSeekBar();
        }
    };

    /**
     * 绑定一些监听和其他的初始化
     */
    private void initialize() {
        mCoverImageView.setOnClickListener(this);
        mWaterMarkLayout.setOnClickListener(this);
        mExitBt.setOnClickListener(this);
        mSaveBt.setOnClickListener(this);
        mAdjustGPUImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mCurId == R.id.filter) {
                    if (mFilterView != null) {
                        mFilterView.dealOnTouch(v, event);
                    }
                    return true;
                } else if (mCurId == R.id.beauty/* || mCurId == R.id.body*/) {
                    if (mBeautyBarView != null) {
                        return mBeautyBarView.dealOnTouch(v, event);
                    }
                }
                return false;
            }
        });
//        mAdjustGPUImageView.setGPUImageOnTouchListener(new AdjustGPUImageView.AdjustGPUImageOnTouchListener() {
//            @Override
//            public void onTouchOpDown() {
//                if (mEyeDecorationView.getVisibility() == VISIBLE) {
//                    mEyeDecorationView.setTouchAble(false);
//                }
//            }
//
//            @Override
//            public void onTouchOpUp() {
//                if (mEyeDecorationView.getVisibility() == VISIBLE) {
//                    mEyeDecorationView.setTouchAble(true);
//                }
//            }
//        });

//        mAdjustGPUImageView.setOnMuscleFollowListener(new AdjustGPUImageView.OnMuscleFollowListener() {
//            @Override
//            public void follow(Matrix matrix) {
//                if (mEyeDecorationView.getVisibility() == VISIBLE) {
//                    mEyeDecorationView.setGpuImageMatrix(matrix);
//                }
//            }
//        });

        if (mIsNeedGoToBeauty) {
//            onOperationClick(R.id.beauty);//初始化addEmoji
        }

//        mImageView.post(new Runnable() {
//            @Override
//            public void run() {
//                mWaterMarkLayout.setVisibility(View.VISIBLE);
//                if (mSrcBitmap != null && mWaterMarkLayout != null) {
//                    //水印View的父View是mImageView的父View
//                    setWaterMarkPosition(ImageRectUtils.getViewRect((View) (mImageView.getParent())), getDrawableRect(mImageView));
//                }
//            }
//        });

        mFilterView.setBaseBitmap(mSrcBitmap.getBitmap());

        dealFunctionMode();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
//        try {
//            String action = intent.getAction();
//            if (!TextUtils.isEmpty(action) && (action.equals(ActionConstant.Actions.ACTION_PICK_TO_ADD_STICKER_EDIT))) {
//                mIsNeedGoToEmojiBar = true;
//                mCheckedStickerPkgName = intent.getStringExtra(ActionConstant.Extras.EXTRA_PACKAGE_NAME);
//
//                if (!TextUtils.isEmpty(mCheckedStickerPkgName)) {
//                    if (mCurId != R.id.addemoji) {
//                        if (mCurId == R.id.filter) {
//                            onCancelClick();
//                        }
//                        onOperationClick(R.id.addemoji);//初始化addEmoji
//                    }
//                    if (getLoadEmojiFinish()) {//已经加载完成
//                        if (mAddEmojiView != null) {
//                            mAddEmojiView.dealSelectEmojiTab(mCheckedStickerPkgName, true);
//                        }
//                    }
//                }
//            }
//        } catch (Throwable e) {
//
//        }
    }

    /**
     * 防止因为内存不足导致的问题
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putParcelable(BEAN, mImageBean);
    }

    /**
     * 将保存的信息进行恢复
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        try {
            super.onRestoreInstanceState(savedInstanceState);
        } catch (Exception e) {
        }
        mImageBean = savedInstanceState.getParcelable(BEAN);
        if (mImageBean == null || mImageBean.mType == MediaTypeUtil.TYPE_VIDEO) {
            finish();
        } else {
            try {
                mSrcBitmap = new CameraDrawable(getResources(), ImageHelper.UriToBitmap(mImageBean));
            } catch (OutOfMemoryError er) {

            }
            if (mSrcBitmap == null || mSrcBitmap.getBitmap() == null) {
                finish();
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
                setConfirmEnable(true);
                refreshBitmap();
            }
        }
    }


    /**
     * 私密相册新增
     */
    @Override
    protected void onStart() {
        super.onStart();
        /*if(mOtherNewFlag != null){
            if(SPDataManager.getEditMagazineNew()
                    || SPDataManager.getShowOtherBeautyRedIcon()) {
                mOtherNewFlag.setVisibility(View.VISIBLE);
            } else{
                mOtherNewFlag.setVisibility(View.GONE);
            }
        }*/
        check2SaveVip(false);
    }

    /**
     * 强制保存
     *
     * @param force
     */
    private void check2SaveVip(boolean force) {
        if (AppVipManager.isVip()) {
            showFilterVipMask(false, false);
            if (mCheck2SaveDoodle && mCurId == R.id.doodle) {
                onConfirmClick();
            } else if (mCheck2SaveWatermark && mCurId == R.id.watermark) {
                onConfirmClick();
            } else if (mCheck2SaveFilter && mCurId == R.id.filter) {
                onConfirmClick();
            } else if (mCurId == R.id.beauty && mBeautyBarView != null) {
                mBeautyBarView.updateVipStatus();
                if (mBeautyBarView.isCheck2Save()) {
                    mBeautyBarView.onConfirmClick();
                }
            }
            if (SPDataManager.getAdOneTimeVip()) {
                SPDataManager.setAdOneTimeVip(false);
            }
            mCheck2SaveDoodle = false;
            mCheck2SaveWatermark = false;
            mCheck2SaveFilter = false;
            if (mBeautyBarView != null) {
                mBeautyBarView.setCheck2Save(false);
            }
        }
    }

//    private long timeCount;

    /**
     * 私密相册新增
     */
    @Override
    protected void onStop() {
        super.onStop();

//        long interval = System.currentTimeMillis()- timeCount;
//        String stayTime;
//        if (interval < 30*1000){
//            stayTime = "(0,30)";
//        }else if (interval < 60*1000){
//            stayTime = "(30,60)";
//        }else if (interval < 120*1000){
//            stayTime = "(60,120)";
//        }else {
//            stayTime = "(120,)";
//        }
//        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_SHOW,
//                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
////                StatisticsConstant.KEY_TREND_FUN, mReportLogic.getFeatureType(),  //todo
//                StatisticsConstant.KEY_STAY_TIME, stayTime);
    }

    /**
     * 统计进入次数
     */
    @Override
    protected void onResume() {
        super.onResume();

        if (mVipMaskView != null && mVipMaskView.getVisibility() == VISIBLE && mVipAnmDrawable != null) {
            mVipAnmDrawable.start();
        }

       /* if(mStickerManager != null){
            LocalStickerData.from = InsideEmojiResource.FROM_EDIT;
            mStickerManager.refreshEmojiData();
        }*/
        StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
                StatisticsConstant.UMENG_CUSTOM_EVENT_VALUE_FEATURE + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
                        SPDataManager.getFunctionEntrance() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SHOW);
        if (SPDataManager.getIsFirstEnterFeature()) {
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
                    StatisticsConstant.UMENG_CUSTOM_EVENT_VALUE_FEATURE + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
                            StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_VALUE_ALL_ + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SHOW);
            SPDataManager.setIsFirstEnterFeature(false);
        }
//        timeCount = System.currentTimeMillis();

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mVipMaskView != null && mVipMaskView.getVisibility() == VISIBLE && mVipAnmDrawable != null) {
            mVipAnmDrawable.stop();
        }
    }

    public boolean openEraseForMixer(boolean open, boolean confirm) {
        boolean success = false;
        if (open && getEraserBar().getVisibility() != View.VISIBLE) {
            Bitmap eraseBitmap = mImageMixerView.getEraseBitmap();
            if (eraseBitmap == null) {
                return false;
            }
            getEraserBar().setVisibility(View.VISIBLE);
            getEraserBar().startAnimation(getBottomIn());
            getMixerBar().startAnimation(getBottomOut());
            getMixerBar().setVisibility(View.GONE);
            showInsideBottomBarWithName(R.string.image_edit_eraser, View.NO_ID);
            success = true;
            mImageEraserView.setSrcBitmap(eraseBitmap, mImageMixerView.getEraseOriginalRect(), mImageMixerView.getEraseContentRect(), mImageMixerView.getEraseBoundRect(), mImageMixerView.getDegree());
            mImageEraserView.setVisibility(View.VISIBLE);
            mImageEraserView.setEraserRefreshBitmapListener(new ImageEraserView.EraserRefreshBitmapListener() {
                @Override
                public void refreshBitmap(Bitmap bitmap, RectF upperRectF, RectF bottomRect) {
                    mImageMixerView.refreshBitmap(bitmap, upperRectF, bottomRect);
                }

            });
            mImageMixerView.intoEraseMode(true);
        } else if (!open && getEraserBar().getVisibility() == View.VISIBLE) {
            getMixerBar().setVisibility(View.VISIBLE);
            getMixerBar().startAnimation(getBottomIn());
            getEraserBar().startAnimation(getBottomOut());
            getEraserBar().setVisibility(View.GONE);
            getEraserBar().reset();
            showInsideBottomBarWithName(R.string.image_edit_mixer, R.drawable.ic_tool_help);
            success = true;
            if (confirm) {
                mImageMixerView.replaceBitmapFromErase(mImageEraserView.getDestBitmapForMixer());
            }
            mImageMixerView.intoEraseMode(false);
            mImageEraserView.setVisibility(View.GONE);
            mImageEraserView.setEraserRefreshBitmapListener(null);
            mImageEraserView.reset();
        }
        return success;
    }

    public void replaceBitmapForMixer() {
        GalleryActivity.startGalleryChangeCollageImages(this, REQUEST_CODE_REPLACE_PIC_2_MIXER);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT_PIC_2_MIXER) {
            if (data != null && resultCode == RESULT_OK) {
                BitmapBean bean = data.getBundleExtra(IMAGE_DATA).getParcelable(IMAGE_DATA);
                if (bean != null) {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (mCurId == R.id.edit) {
                                getEditOperationBar().onMixerImageSelect();
                            } else {
                                mCurId = R.id.op_mixer;
                                showOperationsViewByTabId(mCurId);
                                hideTopView();
                                doShowOperationBarAnim();
                            }
                        }
                    }, 200);
                    mGetBitmapTask = new AsyncTask<Object, Void, Bitmap>() {
                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            showLoading();
                        }

                        @Override
                        protected Bitmap doInBackground(Object... params) {
                            Bitmap result = ImageHelper.getCollageBitmap((BitmapBean) params[0], (Integer) params[1]);
                            return result;
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            super.onPostExecute(bitmap);
                            hideLoading();
                            if (!SPDataManager.hasUseMixer()) {
                                SPDataManager.setHasUseMixer(true);
                            }
                            if (bitmap == null) {
                                return;
                            }
                            mImageMixerView.setBitmaps(mSrcBitmap.getBitmap(), bitmap);
                        }
                    };
                    mGetBitmapTask.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, bean, 2);
                } else {
                    if (mCurId != R.id.edit) {
                        mCurId = View.NO_ID;
                    } else {
                        getEditOperationBar().setSelectedId(View.NO_ID);
                    }
                }
            } else {
                if (mCurId != R.id.edit) {
                    mCurId = View.NO_ID;
                } else {
                    getEditOperationBar().setSelectedId(View.NO_ID);
                }
            }
        } else if (requestCode == REQUEST_CODE_REPLACE_PIC_2_MIXER) {
            if (data != null && resultCode == RESULT_OK) {
                BitmapBean bean = data.getBundleExtra(IMAGE_DATA).getParcelable(IMAGE_DATA);
                if (bean != null) {
                    mGetBitmapTask = new AsyncTask<Object, Void, Bitmap>() {
                        @Override
                        protected void onPreExecute() {
                            super.onPreExecute();
                            showLoading();
                        }

                        @Override
                        protected Bitmap doInBackground(Object... params) {
                            Bitmap result = ImageHelper.getCollageBitmap((BitmapBean) params[0], (Integer) params[1]);
                            return result;
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            super.onPostExecute(bitmap);
                            hideLoading();
                            mImageMixerView.replaceBitmap(bitmap);
                            getMixerBar().setEraserAndMixerBtnEnable(true);
                        }
                    };
                    mGetBitmapTask.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, bean, 2);
                }
            }
        } else if (requestCode == REQUEST_CODE_FOR_VIP_ACTIVITY) {
            if (backFromMaterialVipSubs) {
                SpUtils.obtain().save(EFFECT_NAME, currentFilterBean.getName());
                WDialogShow.showLuckyUserOrInspireAdVideoDialog(this,
                        DialogShow.InspireDialogEntrance.ENTRANCE_3, "", DialogStatistic.AdVideoWhere.VALUE_WHERE_MATERIAL,
                        new IAdVideoDialogListener() {
                            @Override
                            public void onSureClick() {
                                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                                        StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                                SpUtils.obtain().save(EFFECT_NAME, currentFilterBean.getName());
                                DialogStatistic.adVideoSureClick(0);
                            }

                            @Override
                            public void onCancelClick() {
                                DialogStatistic.adVideoCancelClick(0);
                            }

                            @Override
                            public void onCloseClick() {
                                DialogStatistic.adVideoClose(0);
                            }
                        });

                mFromMaterialVip = true;
                mVipMaskWatchVideoView.setVisibility(VISIBLE);
//                if (mVipMaskWatchVideoView != null && mVipMaskWatchVideoView.getVisibility() == View.GONE) {
//                    RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//                    if ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)) {
//                        mVipMaskWatchVideoView.setVisibility(VISIBLE);
//                    }
//                }
            } else {

                WDialogShow.showLuckyUserOrInspireAdVideoDialog(this,
                        DialogShow.InspireDialogEntrance.ENTRANCE_2, "", DialogStatistic.AdVideoWhere.VALUE_WHERE_TOOL,
                        new IAdVideoDialogListener() {
                            @Override
                            public void onSureClick() {
                                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_TOOL,
                                        StatisticsConstant.KEY_FILTER_NAME,"tool");
                                DialogStatistic.adVideoSureClick(1);
                            }

                            @Override
                            public void onCancelClick() {
                                DialogStatistic.adVideoCancelClick(1);
                            }

                            @Override
                            public void onCloseClick() {
                                DialogStatistic.adVideoClose(1);
                            }
                        });
                mFromMaterialVip = false;
            }
        }else{
            if (SpUtils.obtain().getBoolean(SpConstant.IS_FUNCTION_STICKERS, false)) {//贴纸功能订阅页
                SpUtils.obtain().save(SpConstant.IS_FUNCTION_STICKERS, false);
                if ((SPDataManager.getTodayHasShowedAllSubscribeMaskCount() ==1 )) {
                    //每天第一次关闭功能订阅页展示激励视频弹窗
                    DialogShow.showAdVideoDialog(DialogShow.InspireDialogEntrance.ENTRANCE_2, EditorImageActivity.this, "", DialogStatistic.AdVideoWhere.VALUE_WHERE_STICKERS, new IDialog.Listener() {
                        @Override
                        public void yes() {
                            //弹窗展示后,计入统计
                            SPDataManager.setIsShowAdvanceDialog(false);
                            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER,
                                    StatisticsConstant.KEY_FILTER_NAME, StatisticsConstant.VALUE_VIP_FUN_STICKER);
                            SpUtils.obtain().save(EFFECT_NAME, StatisticsConstant.VALUE_VIP_FUN_STICKER);
                        }
                    }, iAdVideoDialogListener1);
                }
            } else {//针对从滤镜素材从功能订阅页返回
                if (mVipMaskWatchVideoView != null ) {
                    mVipMaskWatchVideoView.setVisibility(VISIBLE);
                    if(mVipMaskWatchVideoView.getVisibility()==View.VISIBLE){
                        //模糊页上观看视频按钮可见时统计
                        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                                StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                                StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                    }
                }
                if ((SPDataManager.getTodayHasShowedAllSubscribeMaskCount() ==1 )) {
                    //每天第一次关闭功能订阅页展示激励视频弹窗
                    showIAdDialog();
                }
            }
        }
    }

    public void showIAdDialog(){
        DialogShow.showAdVideoDialog(DialogShow.InspireDialogEntrance.ENTRANCE_2, EditorImageActivity.this, "", DialogStatistic.AdVideoWhere.VALUE_WHERE_MATERIAL, new IDialog.Listener() {
            @Override
            public void yes() {
                //弹窗展示后,计入统计
                SPDataManager.setIsShowAdvanceDialog(false);
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                        StatisticsConstant.KEY_FILTER_NAME, SpUtils.obtain().getString(EFFECT_NAME, ""));

            }
        },iAdVideoDialogListener2);
    }

    IAdVideoDialogListener iAdVideoDialogListener1=new IAdVideoDialogListener() {
        @Override
        public void onSureClick() {
            SpUtils.obtain().save(SpConstant.IS_UNLOCK_STICKERS,true);
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER,
                    StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_VIP_FUN_STICKER);
            SpUtils.obtain().save(EFFECT_NAME, StatisticsConstant.VALUE_VIP_FUN_STICKER);
            DialogStatistic.adVideoSureClick(0);
        }

        @Override
        public void onCancelClick() {
            DialogStatistic.adVideoCancelClick(0);
        }


        @Override
        public void onCloseClick() {
            DialogStatistic.adVideoClose(0);
        }
    };

    IAdVideoDialogListener iAdVideoDialogListener2=new IAdVideoDialogListener() {
        @Override
        public void onSureClick() {
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_POPUP,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                    StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
            SpUtils.obtain().save(EFFECT_NAME, currentFilterBean.getName());
            DialogStatistic.adVideoSureClick(0);
        }

        @Override
        public void onCancelClick() {
            DialogStatistic.adVideoCancelClick(0);
        }


        @Override
        public void onCloseClick() {
            DialogStatistic.adVideoClose(0);
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showStickersFunctionSubscribe(StickersTurnToFunctionSubscribeEvent event){
        SVipController.showFunctionSubscribe(EditorImageActivity.this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_STICKER,null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showStickersReward(StickersTurnToRewardEvent event) {
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_STICKER,
                StatisticsConstant.KEY_FILTER_NAME,event.getStickerPkgname());
        SpUtils.obtain().save(ISFROMBUTTON, true);
        SpUtils.obtain().save(EFFECT_NAME, event.getStickerPkgname());
        getRewardAdManager().showRewardAdVideo();
    }

    private boolean backFromMaterialVipSubs;
    private boolean mFromMaterialVip;

    public void setBackFromVipTool() {
        backFromMaterialVipSubs = false;
    }

    /**
     * 显示ProgressDialog
     */
    private void showShareProgressDialog() {
        if (mShareProgressDialog == null) {
            View v = getLayoutInflater().inflate(R.layout.progress_bar, null, false);
            mShareProgressDialog = new ProgressDialog(EditorImageActivity.this, ProgressDialog.THEME_TRADITIONAL);
            mShareProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mShareProgressDialog.setCancelable(true);
            mShareProgressDialog.setCanceledOnTouchOutside(false);
            mShareProgressDialog.show();
            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.gravity = Gravity.CENTER;
            mShareProgressDialog.setContentView(v, lp);
            mShareProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!isFinishing()) {
                        finish();
                    }
                }
            });
        } else {
            mShareProgressDialog.show();
        }
    }

    /**
     * 隐藏ProgressDialog
     */
    private void dismissShareProgressDialog() {
        if (mShareProgressDialog != null && mShareProgressDialog.isShowing()) {
            mShareProgressDialog.dismiss();
        }
    }

    public void clickedButton(View view) {
        if (mFilterView != null) {
//            mFilterView.clickedButton(view);
        }
    }

    @Override
    public void onClick(View v) {
        if (mSrcBitmap == null || mSrcBitmap.getBitmap() == null || mSrcBitmap.getBitmap().isRecycled()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.exit) {
            if (mNeedSave) {
                showExitAlertDialog();
            } else {
                onExit();
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_CANCEL_CLICK);
        } else if (id == R.id.save) {
            doSave();
        } else if (id == R.id.cancel) {
            onCancelClick();

        } else if (id == R.id.confirm) {
            onConfirmClick();

        } else if (id == R.id.watermark_layout) {
            if (mCurId == R.id.watermark) {
                return;
            }
            if (mIsNeedGoToBeauty) {
                //在eidt的watermark模块里，再点击水印，没有效果
                if (getEditOperationBar().isSelectWatermark()) {
                    return;
                }
                mCurId = R.id.edit;
                getEditOperationBar().clickWatermark();
                return;
            } else {
                mCurId = R.id.watermark;
                showOperationsViewByTabId(R.id.watermark);
                setConfirmEnable(true);
                showInsideBottomBarWithName(R.string.more_settings_watermark, View.NO_ID);
                if (!mWatermarkManager.isWatermarkExist()) {
                    mWaterMarkIV.setImageBitmap(null);
                }
                hideTopView();
                doShowOperationBarAnim();
                StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_WATERMARK_CLICK);
            }
        } else if (id == R.id.flip_horizontal) {
            if (mCanvasEditEmojiView.getBeans() != null && mCanvasEditEmojiView.getBeans().size() > 0) {
                mCanvasEditEmojiView.doFlip(true);
            }
        } else if (id == R.id.flip_vertical) {
            if (mCanvasEditEmojiView.getBeans() != null && mCanvasEditEmojiView.getBeans().size() > 0) {
                mCanvasEditEmojiView.doFlip(false);
            }
        } else if (id == R.id.rotate_right) {
            if (mCanvasEditEmojiView.getBeans() != null && mCanvasEditEmojiView.getBeans().size() > 0) {
                mCanvasEditEmojiView.doRotate(90);
            }
        } else if (id == R.id.layer_up) {
            if (mCanvasEditEmojiView.getBeans() != null && mCanvasEditEmojiView.getBeans().size() > 0) {
                mCanvasEditEmojiView.doLayerUp();
            }
        } else if (id == R.id.layer_down) {
            if (mCanvasEditEmojiView.getBeans() != null && mCanvasEditEmojiView.getBeans().size() > 0) {
                mCanvasEditEmojiView.doLayerDown();
            }
        } else if (id == R.id.iv_cover) {
//            if (mIsEmojiPanelShow) {
//                mIsEmojiPanelShow = false;
//                mAddEmojiView.setEmojiPanelVisible(false, true);
//            }
        } else {
            onOperationClick(id);
        }
    }

    private void doSave() {
        if ((mNeedSave || mWaterMarkIsExist || mIsNeedPublish || AppVipManager.isVip()) && mSrcBitmap != null) {
            //设置成不可点击 防止多次保存
            mSaveBt.setEnabled(false);

//				mNeedSave = false;

            final String path = FolderHelper.getOrCreateSaveLocation();

            if (!mIsNeedPublish && !mIsNeedShare) {
            }
            if (!mNeedSave && mIsNeedPublish) {
                getSaveToTempAndPublishTask().execute();
            } else {
                String name = FileUtil.EDIT_IAMGE_FILE_NAME + ImageHelper.CountDate(System.currentTimeMillis()) + ".jpg";
                if (mHasDateMark) {
                    name = DateMaskUtil.addDateMark(name);
                }
                mSaveTask = getSaveTask().execute(path, name);
            }
//            String currentFilterName = getCurrentFilterName();
//            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_SAVE_CLICK);
//            if (!ImageFilterTools.FILTER_NAME_DEFAULT.equals(currentFilterName)) {
//                StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_FILTER
//                        + currentFilterName);
//            }
//            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
//                    StatisticsConstant.UMENG_CUSTOM_EVENT_VALUE_FEATURE + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                            SPDataManager.getFunctionEntrance() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SAVE);
//            if (SPDataManager.getIsFirstSaveFeature()) {
//                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
//                        StatisticsConstant.UMENG_CUSTOM_EVENT_VALUE_FEATURE + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_VALUE_ALL_ + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SAVE);
//                SPDataManager.setIsFirstSaveFeature(false);
//            }
//            if (TextUtils.equals(SPDataManager.getFunctionEntrance(), StatisticsConstant.MAIN_BTN_EDIT)) {
//                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
//                        StatisticsConstant.MAIN_BTN_EDIT + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                                SPDataManager.getSaveFunctionName() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SAVE);
//                SPDataManager.setSaveFunctionName("no_function");
//            } else {
//                StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_EDITOR, StatisticsConstant.UMENG_CUSTOM_KEY_FUNCTION,
//                        StatisticsConstant.MAIN_BTN_BEAUTY + StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                                SPDataManager.getSaveFunctionName() + StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_SAVE);
//                SPDataManager.setSaveFunctionName("no_function");
//            }

            String NFEditEnterType = "";
            switch (mOtherBarView.getCurrentTypeId()) {
                case OtherBarView.BarType.TYPE_ID_EFFECT:
                    if (tabId == R.id.filter)
                        NFEditEnterType = StatisticsConstant.ENTRANCE_VALUE_FILTER;
                    else
                        NFEditEnterType = StatisticsConstant.MAIN_BTN_EFFECT;
                    break;
                case OtherBarView.BarType.TYPE_ID_ADJUST:
                    NFEditEnterType = StatisticsConstant.MAIN_BTN_ADJUST;
                    break;
                case OtherBarView.BarType.TYPE_ID_EDIT:
                    NFEditEnterType = StatisticsConstant.MAIN_BTN_EDIT;
                    break;
            }
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SAVE,
                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                    StatisticsConstant.KEY_EDIT_TOOL, getEditTool());

            int saveCount = SpUtils.obtain().getInt("edit_save", 0);
            if (saveCount < 2) {
                SpUtils.obtain().save("edit_save", saveCount + 1);
            }
        }
    }

    private String getEditTool() {
        switch (tabId) {
            case R.id.filter:
                return "filter";
            case R.id.mirror:
                return "mirror";
            case R.id.watermark:
                return "watermark";
            case R.id.beauty:
                return "beauty";
            case R.id.addtext:
                return "text";
            case R.id.tilt_shift:
                return "blur";
            case R.id.adjust:
                return "adjust";
            case R.id.crop:
                return "crop";
            case R.id.rotate:
                return "rotate";
            default:
                return "known";
        }
    }

    /**
     * 点击cancel
     */
    private void onCancelClick() {
        if (mCurId == R.id.adjust) {
            if (getAdjustBarView().cancelFilter()) {
                showInsideBottomBarWithName(R.string.image_edit_adjust, View.NO_ID);
                setConfirmEnable(getAdjustBarView().isModified());
                return;
            } else {
                mFilterCallBackListener.cancel();
            }
        } else if (mCurId == R.id.filter) {
            showFilterVipMask(false, false);

            mFilterView.reset();
            mFilterCallBackListener.cancel();
        } else if (mCurId == R.id.crop) {
            mFilterCallBackListener.cancel();
        } else if (mCurId == R.id.rotate) {
            if (mRotateBarView != null) {
                mRotateBarView.restore();
            }
            mFilterCallBackListener.cancel();
//        } else if (mCurId == R.id.addemoji) {
//            if (mAddEmojiView != null && mAddEmojiView.getEmojiPanelButNotInit() != null) {
//                mAddEmojiView.setEmojiPanelVisible(false, true);
//                mAddEmojiView.restore(false);
//            }
//            mCanvasEditEmojiView.reset();
//            mFilterCallBackListener.cancel();
        } else if (mCurId == R.id.doodle) {
            mGraffitoView.reset();
            mFilterCallBackListener.cancel();
//        } else if(mCurId == R.id.op_eraser) {
//            mImageEraserView.reset();
//            getEraserBar().reset();
        } else if (mCurId == R.id.op_mixer) {
            if (mMixerBarView != null && mMixerBarView.onCancelClick()) {
                if (openEraseForMixer(false, false)) {
                    return;
                }
                mImageMixerView.reset();
                getMixerBar().reset();
                resetGPUImageView();
            } else {
                return;
            }
        } else if (mCurId == R.id.tilt_shift) {
            getTiltShiftBarView().cancel();
            mFilterCallBackListener.cancel();
        } else if (mCurId == R.id.addtext) {
            mCanvasEditTextView.reset();
            mFilterCallBackListener.cancel();
        } else if (mCurId == R.id.beauty/* || mCurId == R.id.body*/) {
            boolean isCancel = mBeautyBarView.onCancelClick();
            if (isCancel) {
                if (mIsNeedGoToBeauty) {
                    if (mNeedSave) {
                        showExitAlertDialog();
                    } else {
                        statisticsMainBtnEditBack();
                        finish();
                    }
                    return;
                }
                resetGPUImageView();
                mFilterCallBackListener.cancel();
            } else {
                return;
            }
        } else if (mCurId == R.id.watermark) {
            if (mIsNeedGoToBeauty) {
                //此版本中，让Edit模块来处理这个事件
                mCurId = R.id.edit;
            } else {
                Watermark watermark = null;
                if (mHasUserModify || !mHasDateMark) {
                    watermark = mWatermarkManager.getCurrentWatermark();
                }
                if (mWatermarkManager.isPlaceholderWatermark(watermark)) {//没有水印
                    mWaterMarkIsExist = false;
                    mWaterMarkIV.setImageBitmap(null);
                } else {
                    mWaterMarkIsExist = true;
                    Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
                    if (bitmap != null) {
                        mWaterMarkIV.setImageBitmap(bitmap);
                    }
                }
                refreshWaterMark();
            }
        } else if (mCurId == R.id.mirror) {
            mMirrorBarView.reset();
        } else if (mCurId == R.id.edit) {
            boolean isCancel = getEditOperationBar().onCancelClick();
            if (!isCancel) {
                return;
            }
        } else if (mCurId == R.id.sticker){
            if (mAddEmojiView != null) {
                mAddEmojiView.restore(false);
            }
        } else {
            mFilterCallBackListener.cancel();
        }

        /*if (mIsNeedGoToBeauty && (mCurId == R.id.addemoji || mCurId == R.id.filter || mCurId == R.id.edit)) {

        } else*/
        {
            mCurId = View.NO_ID;
        }
        showTopView();
        doHideOperationBarAnim();

        /*if (mIsNeedGoToBeauty && (mCurId == R.id.addemoji || mCurId == R.id.filter || mCurId == R.id.edit)) {
            showOperationsViewByTabId(mCurId);
        } else */
        {
            updateBottomTabSelectStatus(mCurId);
        }

        if (mNeedSave || mWaterMarkIsExist) {
            setSaveBtEnable(true);
        } else {
            setSaveBtEnable(false);
        }
    }

    /**
     * 点击应用
     */
    private void onConfirmClick() {
        if (mCurId == R.id.adjust) {
            if (getAdjustBarView().onConfirmClick()) {
                showInsideBottomBarWithName(R.string.image_edit_adjust, View.NO_ID);
                setConfirmEnable(getAdjustBarView().isModified());
                return;
            }
            Bitmap bitmap = mAdjustGPUImageView.getCurrentBitmap();
            getAdjustBarView().cancelFilter();
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mAdjustUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            mNeedSave = true;
        } else if (mCurId == R.id.filter) {
            if (mSrcBitmap != null) {
                if (mVipMaskView != null && mVipMaskView.getVisibility() == VISIBLE && !AppVipManager.isVip()) {
                    backFromMaterialVipSubs = true;
                    mCheck2SaveFilter = true;
                    SVipController.showFunctionSubscribe(this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_FILTER,null);
                    return;
                }
                showFilterVipMask(false, false);
                getLoadingView().startLoading();
                findViewById(R.id.mask_view).setVisibility(View.VISIBLE);
                ThreadPool.runOnNonUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mUseEffectInfo != null) {
                            FilterCategoryBean currentFilterCategoryBean = mFilterView.getCurrentFilterCategoryBean();
                            if (currentFilterCategoryBean != null) {
                                mUseEffectInfo.add(currentFilterCategoryBean);
                                mUsedStickerAndFilter.add(currentFilterCategoryBean.getName());
                            }
                        }
                        GPUImageFilter filter = mFilterView.newCurrentFilter();
                        Bitmap bitmap = mAdjustGPUImageView.getCurrentBitmap(mSrcBitmap.getBitmap(), filter);
                        bitmap = BitmapUtils.copyBitmap(bitmap);
                        final Bitmap finalBitmap = bitmap;
                        ThreadPool.runUITask(new Runnable() {
                            @Override
                            public void run() {
                                getLoadingView().stopLoading();
                                findViewById(R.id.mask_view).setVisibility(View.GONE);
                                CameraDrawable cd = new CameraDrawable(getResources(), finalBitmap);
                                mImageView.setImageDrawable(cd);
                                mSrcBitmap = cd;

                                mFilterUsed = true;
                                //refreshBitmap()方法是重新设置mAdjustGPUImageView的bitmap
                                //点击应用的时候，mAdjustGPUImageView已经绘制好了，没必要再次绘制
//                                refreshBitmap();

                                updateBottomTabSelectStatus(mCurId);
                                getEditOperationBar().updateSrcBitmap(cd);
                                getEditOperationBar().setVisibility(View.GONE);
                                //showBottomBar(true, BottomInsideBarView.TYPE_NAME);
                                showTopView();
                                doHideOperationBarAnim();
                                //FilterBarView的reset()方法会使用最原始的GPUImageFilter重新绘制
                                //这里是和上一步refreshBitmap()配合使用的，上面的注释掉了，这一步也没必要了
//                                mFilterView.reset();
                                mFilterCallBackListener.cancel();
                            }
                        });
                    }
                });
                mNeedSave = true;
            }
        } else if (mCurId == R.id.crop) {
            resetGPUImageView();
            Bitmap bitmap = mImageView.getCroppedImage();
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                bitmap = ImageHelper.getScaleBitmap(bitmap);
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);

                if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mCropUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            mNeedSave = true;
        } else if (mCurId == R.id.rotate) {
            resetGPUImageView();
            Bitmap bitmap = mRotationImagView.getCurrentBitmap();
            if (mRotateBarView != null) {
                mRotateBarView.restore();
            }
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                mRotationImagView.setImageDrawable(cd);
                if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mRotateUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            mNeedSave = true;
        } else if (mCurId == R.id.sticker) {
            if (mAddEmojiView != null && mAddEmojiView.getEmojiPanelButNotInit() != null) {
                if (mIsNeedGoToBeauty) {
                    mAddEmojiView.setEmojiPanelVisible(false, true);
                } else {
                    mAddEmojiView.setEmojiPanelVisible(false, false);
                }
                mAddEmojiView.restore(false);
            }
            if (mAddEmojiView != null) {
                // 判断有没有apk子包对应的一些emoji
                if (mUseEffectInfo != null) {
                    LinkedList<ContainerBean> beans = mCanvasEditEmojiView.getBeans();
                    if (beans != null) {
                        for (ContainerBean bean : beans) {
                            if (bean instanceof EditEmojiBean) {
                                EmojiBean emojiBean = ((EditEmojiBean) bean).getEmojiBean();
                                if (emojiBean != null) {
                                    mUseEffectInfo.add(emojiBean);
                                    mUsedStickerAndFilter.add(emojiBean.getPackageName());
                                }
                            }
                        }
                    }
                }
                if (mCanvasEditEmojiView.hasGif()) {
                    if(!SPDataManager.hasSaveGif()) {
                        showCheckGifToVideoDialog();
                        SPDataManager.setHasSaveGif();
                    } else {
                        saveGifToVideo();
                    }
                    return;
                } else {
                    Bitmap bitmap = mCanvasEditEmojiView.getDstBitmap(0);
                    mCanvasEditEmojiView.reset();
                    if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                        CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                        mImageView.setImageDrawable(cd);
                        mCoverImageView.setImageDrawable(cd);
                        mCanvasEditEmojiView.setImageBitmap(bitmap);
                        if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                        mSrcBitmap.recycle();
                        }
                        mSrcBitmap = cd;
                        getEditOperationBar().updateSrcBitmap(cd);
                        getEditOperationBar().setVisibility(View.GONE);
                        mStickerUsed = true;
                    } else {
                        mImageView.setImageDrawable(mSrcBitmap);
                        mCoverImageView.setImageDrawable(mSrcBitmap);
                    }
                    mNeedSave = true;
                }
            } else {
                mCanvasEditEmojiView.reset();
            }
        } else if (mCurId == R.id.doodle) {
            if (!AppVipManager.isVip() && mGraffitoView.hasUseVipBrush()) {
                mCheck2SaveDoodle = true;
                backFromMaterialVipSubs = false;
                SVipController.showSubscribeActivity(this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_DOODLE);
                return;
            }
            Bitmap bitmap = mGraffitoView.getContentBitmap();
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mDoodleUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            mGraffitoView.reset();
            mNeedSave = true;
//        } else if(mCurId == R.id.op_eraser) {
//            Bitmap bitmap = mImageEraserView.getDestBitmap();
//            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
//                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
//                mImageView.setImageDrawable(cd);
//                mSrcBitmap = cd;
//                mEraserUsed = true;
//            } else {
//                mImageView.setImageDrawable(mSrcBitmap);
//            }
//            mImageEraserView.reset();
//            getEraserBar().reset();
//            mNeedSave = true;
        } else if (mCurId == R.id.op_mixer) {
            if (mMixerBarView == null) {
                return;
            }
            boolean isConfirm = mMixerBarView.onConfirmClick();
            if (isConfirm) {
                if (openEraseForMixer(false, true)) {
                    return;
                }
                Bitmap bitmap = mImageMixerView.getDestBitmap();
                if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                    CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                    mImageView.setImageDrawable(cd);
                    mSrcBitmap = cd;
                    mMixerUsed = true;
                } else {
                    mImageView.setImageDrawable(mSrcBitmap);
                }
                mImageMixerView.reset();
                getMixerBar().reset();
                resetGPUImageView();
                mNeedSave = true;
            } else {
                return;
            }
        } else if (mCurId == R.id.tilt_shift) {
            Bitmap bitmap = mAdjustGPUImageView.getCurrentBitmap();
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mBlurUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            getTiltShiftBarView().cancel();
            mNeedSave = true;
        } else if (mCurId == R.id.addtext) {
            if (mAddTextView != null) {
                Bitmap bitmap = mCanvasEditTextView.getDstBitmap();
                mCanvasEditTextView.reset();
                if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                    CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                    mImageView.setImageDrawable(cd);
                    mCanvasEditTextView.setImageBitmap(bitmap);
                    if (mSrcBitmap != null/* && !mSrcBitmap.isRecycled()*/) {
//                        mSrcBitmap.recycle();
                    }
                    mSrcBitmap = cd;
                    mTextUsed = true;
                } else {
                    mImageView.setImageDrawable(mSrcBitmap);
                }
                mNeedSave = true;
            } else {
                mCanvasEditTextView.reset();
            }
        } else if (mCurId == R.id.watermark) {
            Watermark watermark = mWatermarkManager.getTempWatermark();
            if (watermark == null) {
                watermark = mWatermarkManager.getCurrentWatermark();
            }
            if (mWatermarkManager.isPlaceholderWatermark(watermark)) {//没有水印
                if (!AppVipManager.isVip()) {
                    mCheck2SaveWatermark = true;
                    backFromMaterialVipSubs = false;
                    SVipController.showSubscribeActivity(this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_WATERMARK);
                    return;
                }
                mWaterMarkIV.setImageBitmap(null);
            } else {
                Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
                if (bitmap != null) {
                    mWaterMarkIV.setImageBitmap(bitmap);
                }
            }
            mWatermarkManager.setCurrentWatermark(watermark);
            mWatermarkManager.setTempWatermark(null);
            mNeedSave = true;
            refreshWaterMark();
            mWatermarkManager.saveLastUseWatermark();
            mHasUserModify = true;
        } else if (mCurId == R.id.beauty /*|| mCurId == R.id.body*/) {
            boolean isConfirm = mBeautyBarView.onConfirmClick();
            if (mIsNeedGoToBeauty) {
                mBeautyBarView.setVisibility(VISIBLE);
                getEditOperationBar().setVisibility(View.GONE);
            }
            if (isConfirm) {
                Bitmap bitmap = mBeautyBarView.getCurrentBitmap();
                if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                    CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                    mImageView.setImageDrawable(cd);
                    mCoverImageView.setImageDrawable(cd);
                    mSrcBitmap = cd;
                    mBeautyUsed = true;
                } else {
                    mImageView.setImageDrawable(mSrcBitmap);
                    mCoverImageView.setImageDrawable(mSrcBitmap);
                }
                mNeedSave = true;
                if (!mIsNeedGoToBeauty) {
                    mBeautyBarView.reset();
                }
            } else {
                return;
            }
        } else if (mCurId == R.id.mirror) {
            resetGPUImageView();
            Bitmap bitmap = mMirrorView.getCollageBitmap();
            if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
                CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
                mImageView.setImageDrawable(cd);
                if (mSrcBitmap != null) {
//                    mSrcBitmap.recycle();
                }
                mSrcBitmap = cd;
                mMirrorUsed = true;
            } else {
                mImageView.setImageDrawable(mSrcBitmap);
            }
            mMirrorBarView.reset();
            mNeedSave = true;
        } else if (mCurId == R.id.edit) {
            boolean isConfirm = getEditOperationBar().onConfirmClick();
            //confirm 失败的情况
            if (!isConfirm) {
                return;
            }
        } else {
            mFilterCallBackListener.applyed();
        }

        if (mCurId == R.id.filter /*|| mCurId == R.id.addemoji*/) {
//            if (mIsNeedGoToBeauty && mCurId == R.id.addemoji) {
//                showTopView();
//                doHideOperationBarAnim();
//                mCanvasEditEmojiView.forceInit(ImageRectUtils.getViewRect(mCanvasEditEmojiView));
//            }
            if (!mIsNeedGoToBeauty) {
//                mBottomLayoutBeauty.changeTabState(-1);
//                if (mAddEmojiView != null) {
//                    getAddEmojiBarView().setVisibility(View.GONE);
//                }
                mFilterView.setVisibility(View.GONE);
            }
        }

        if (mCurId != R.id.filter) {
            if (!mIsNeedGoToBeauty) {
                mCurId = View.NO_ID;
            }

            //edit模块自己处理下述更新内容
            if (mCurId != R.id.edit) {
                updateBottomTabSelectStatus(mCurId);
                refreshBitmap();
            }

            if (!mIsNeedGoToBeauty) {
                showTopView();
                doHideOperationBarAnim();
            }
        }

        if (!mIsNeedGoToBeauty) {
            mCurId = View.NO_ID;
        }

        if (mNeedSave || mWaterMarkIsExist) {
            setSaveBtEnable(true);
        } else {
            setSaveBtEnable(false);
        }
    }

    public void refreshBitmapOfBeauty() {
        Bitmap bitmap = getBeautyBarView().getCurrentBitmap();
        if (bitmap != null && bitmap != mSrcBitmap.getBitmap()) {
            CameraDrawable cd = new CameraDrawable(getResources(), bitmap);
            mImageView.setImageDrawable(cd);
            mCoverImageView.setImageDrawable(cd);
            mSrcBitmap = cd;
            mBeautyUsed = true;
        } else {
            mImageView.setImageDrawable(mSrcBitmap);
            mCoverImageView.setImageDrawable(mSrcBitmap);
        }
        mNeedSave = true;
    }


    private AlertDialog mCheckDialog;

    private void showCheckGifToVideoDialog() {
        if (mCheckDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(EditorImageActivity.this);
            /*builder.setNegativeButton(R.string.image_edit_exit_dialog_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mCheckDialog.dismiss();
                }
            });*/
            builder.setPositiveButton(R.string.check_gif_to_video_sure, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mCheckDialog.dismiss();
                    saveGifToVideo();
                }
            });
            builder.setTitle(R.string.image_edit_exit_dialog_title);
            builder.setMessage(R.string.check_gif_to_video_message);
            mCheckDialog = builder.create();
            mCheckDialog.setCancelable(true);
            mCheckDialog.setCanceledOnTouchOutside(true);
            mCheckDialog.show();
            FontUtil.setAlertDialogCustomFont(mCheckDialog);
        } else {
            mCheckDialog.show();
        }
    }

    private ProgressDialog mCoverView;

    private void saveGifToVideo() {
        if (mCoverView == null) {
            mCoverView = DialogUtils.showCoverProgressDialog(this);
        } else {
            mCoverView.show();
        }
        mStickerUsed = true;
        SPDataManager.setSaveGif(true);

        getLoadingView().startLoading();
        mCanvasEditEmojiView.stopGif();
        if (mCanvasEditTextView != null) {
            mCanvasEditTextView.statistics();
        }

//        ThreadPool.runOnNonUIThread(new Runnable() {
//            @Override
//            public void run() {
//
//                File destFile = FolderHelper.getOutputMediaFile(ImageEditActivity.this, FolderHelper.MEDIA_TYPE_DYNAMIC, false);
//
//                GifGPUImageFilter gifGPUImageFilter = new GifGPUImageFilter(mCanvasEditEmojiView);
//                gifGPUImageFilter.setNeedRecycle(false);
//                final int[] outputSize = Gif2VideoUtils.getVideoOutputSize(mSrcBitmap.getBitmap().getWidth(), mSrcBitmap.getBitmap().getHeight());
//                final long time = System.currentTimeMillis();
//                Gif2VideoUtils.gif2Video(destFile, gifGPUImageFilter,
//                        outputSize[0], outputSize[1],
//                        mCanvasEditEmojiView.getFrame(), mCanvasEditEmojiView.getDuration(),
//                        new VideoFilterDevice.ResultCallback() {
//                            @Override
//                            public void onError() {
//                                StatisticsUtils.statisticsMakeVideoResult(ImageEditActivity.class.getSimpleName(), false, outputSize[0], outputSize[1]);
//                                ThreadPool.runUITask(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if (mCanvasEditEmojiView != null) {
//                                            mCanvasEditEmojiView.startGif();
//                                            mCanvasEditEmojiView.releaseCacheBitmap();
//                                            getLoadingView().stopLoading();
//                                        }
//                                        if (mCoverView != null) {
//                                            mCoverView.dismiss();
//                                        }
//                                    }
//                                });
//                            }
//
//                            @Override
//                            public void onSuccess(final File outputFile) {
//                                boolean isBroken = FileUtil.checkVideoIsBroken(outputFile.getAbsolutePath());
//                                StatisticsUtils.statisticsMakeVideoResult(ImageEditActivity.class.getSimpleName(), !isBroken, outputSize[0], outputSize[1]);
//                                if (isBroken) {
//                                    onSaveFail(outputFile.getAbsolutePath());
//                                    return;
//                                }
//                                ThreadPool.runUITask(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        if (isFinishing()) {
//                                            return;
//                                        }
//                                        if(getLoadingView() != null) {
//                                            getLoadingView().stopLoading();
//                                        }
//                                        if (mCoverView != null) {
//                                            mCanvasEditEmojiView.releaseCacheBitmap();
//                                            mCoverView.dismiss();
//                                        }
//
//                                        TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
//                                            @Override
//                                            public void run() {
//                                                statisticsSave();
//                                                Bundle bundle = null;
//                                                if (mUseEffectInfo != null) {
////                                                    bundle = RateGuide.newBundle(mOriginalFilePath,
////                                                            MediaTypeUtil.TYPE_OTHER_IMAGE,
////                                                            outputFile.getAbsolutePath(),
////                                                            MediaTypeUtil.TYPE_VIDEO,
////                                                            mUseEffectInfo);
//                                                }
//
//
//                                                if (mIsFromOthers || mIsNeedStartPreview || mIsNeedGoToEmojiBar || mIsNeedGoToBeauty || mNeedToApplyFilter) {
//                                                    Intent i = new Intent();
//                                                    if (bundle != null) {
//                                                        i.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, bundle);
//                                                    }
//                                                    setResult(RESULT_OK, i);
//                                                } else {
//                                                    //把之前的预览界面关闭
//                                                    Intent i = new Intent();
//                                                    if (bundle != null) {
//                                                        i.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, bundle);
//                                                    }
//                                                    i.putExtra("finish", "finish");
//                                                    setResult(RESULT_OK, i);
//                                                }
//                                                if (mWatermarkManager != null) {
//                                                    VideoEditActivity.startVideoEditActivityFromGif(
//                                                            ImageEditActivity.this,
//                                                            outputFile.getAbsolutePath(),
//                                                            mWatermarkManager.getCurrentWatermark(),
//                                                            mOriginalFilePath, MediaTypeUtil.TYPE_OTHER_IMAGE,
//                                                            mUseEffectInfo);
//                                                }
//                                                finish();
//                                            }
//                                        };
//                                        onSave(taskRunnable);
//                                    }
//                                });
//                            }
//                        });
//            }
//        });

    }

    private void onSaveFail(String filePath) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (FileUtil.isLowStorageSize()) {
                    // 存储空间不足
                    Toast.makeText(ComponentContext.getContext(), R.string.little_sdcard_tips, Toast.LENGTH_SHORT).show();
                } else if (!FileUtil.canWriteExternalStorage()) {
                    // 没有读写存储卡权限
                    Toast.makeText(ComponentContext.getContext(), R.string.no_sdcard_permission, Toast.LENGTH_SHORT).show();
                } else {
                    // 其他原因，提示用户重试
                    Toast.makeText(ComponentContext.getContext(), R.string.save_video_fail_unkonwn_reason, Toast.LENGTH_SHORT).show();
                }
                if (mCanvasEditEmojiView != null) {
                    mCanvasEditEmojiView.startGif();
                    mCanvasEditEmojiView.releaseCacheBitmap();
                    getLoadingView().stopLoading();
                }
                if (mCoverView != null) {
                    mCoverView.dismiss();
                }
            }
        });
    }

    /**
     * 操作按钮的点击
     *
     * @param id
     */
    private void onOperationClick(int id) {
        if (mCurId == id) return;
        mCurId = id;

        /**
         *在piccollage版本，beauty模块里，点击底部栏，从sticker或filter跳转到其他页面时，需要重置一些状态
         */
        if (mIsNeedGoToBeauty && (/*mLastId == R.id.addemoji ||*/ mLastId == R.id.filter)) {
            resetFromLastModule(mLastId);
            if (mBeautyBarView == null) {
                getBeautyBarView();
            }
            mBeautyBarView.resetWithoutAnimation();
            if (mTopView.getVisibility() != View.VISIBLE) {
                mTopView.setVisibility(View.VISIBLE);
                mTopView.startAnimation(getTopIn());
            }
            mLastId = mCurId;
        }

        if (mCurId == R.id.adjust) {
            showInsideBottomBarWithName(R.string.image_edit_adjust, View.NO_ID);
            setConfirmEnable(false);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_PARAM_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.filter) {
//            initBottomBeautyMenu();
//            mBottomLayoutBeauty.changeTabState(R.id.filter);
            /*if (mIsNeedGoToBeauty) {
                mBottomLayoutBeauty.changeTabState(mCurId);
                mLastId = mCurId;
            } else */
            {
                showInsideBottomBarWithName(R.string.image_edit_filter, View.NO_ID);
            }
            setConfirmEnable(false);
            Bitmap bitmap = mFilterView.getBaseBitmap();
            if (mSrcBitmap != null && (bitmap == null || bitmap != mSrcBitmap.getBitmap())) {//说明两边不一致  需要刷新
                mFilterView.setBaseBitmap(mSrcBitmap.getBitmap());
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_FILTER_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.crop) {
            showInsideBottomBarWithName(R.string.image_edit_crop, View.NO_ID);
            setConfirmEnable(true);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_CROP_CLICK);
            SPDataManager.setClickCropBtn(true);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.rotate) {
            showInsideBottomBarWithName(R.string.image_edit_rotate, View.NO_ID);
            setConfirmEnable(false);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_ROTATE_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.sticker) {
            showInsideBottomBarWithName(R.string.image_edit_sticker, View.NO_ID);
            setConfirmEnable(false);
//            Bitmap bitmap = mFilterView.getBaseBitmap();
//            if (mSrcBitmap != null && (bitmap == null || bitmap != mSrcBitmap.getBitmap())) {//说明两边不一致  需要刷新
//                mFilterView.setBaseBitmap(mSrcBitmap.getBitmap());
//            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_FILTER_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);

////            initBottomBeautyMenu();
////            mBottomLayoutBeauty.changeTabState(R.id.addemoji);
//            //showInsideBottomBarWithName(R.string.image_edit_sticker);
//
//            if (mIsNeedGoToBeauty) {
////                mBottomLayoutBeauty.changeTabState(mCurId);
//                mLastId = mCurId;
//            } else {
////                showInsideBottomBarWithButton();
//            }
//            setConfirmEnable(false);
//            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_STICKERS_CLICK);
//            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.doodle) {
            showInsideBottomBarWithName(R.string.image_edit_doodle, View.NO_ID);
            setConfirmEnable(false);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_DOODLE_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
//        } else if(mCurId == R.id.op_eraser) {
//            showInsideBottomBarWithName(R.string.image_edit_eraser, View.NO_ID);
//            setConfirmEnable(false);
//            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_ERASER_CLICK);
        } else if (mCurId == R.id.op_mixer) {
            GalleryActivity.startGalleryChangeCollageImages(this, REQUEST_CODE_SELECT_PIC_2_MIXER);
            showInsideBottomBarWithName(R.string.image_edit_mixer, R.drawable.ic_tool_help);
            setConfirmEnable(true);
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_MIXER_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.tilt_shift) {
            showInsideBottomBarWithName(R.string.image_edit_adjust_tiltshift, View.NO_ID);
            setConfirmEnable(true);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_BLUR_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.addtext) {
            showInsideBottomBarWithName(R.string.image_preview_text, View.NO_ID);
            setConfirmEnable(false);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_TEXT_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.watermark) {
            showInsideBottomBarWithName(R.string.watermark, View.NO_ID);
            setConfirmEnable(true);
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_TOOL_EDITOR_WATERMARK_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.beauty/* || mCurId == R.id.body*/) {
            if (mWaterMarkLayout != null && mShowWatermark) {
                setWaterMarkVisible(false);
            }

            if (mCurId == R.id.beauty) {
                getBeautyBarView().chageStateType(BeautyBarView.TYPE_BEAUTY);
            } else {
                getBeautyBarView().chageStateType(BeautyBarView.TYPE_BODY);
            }
            if (mIsNeedGoToBeauty) {
//                mBottomLayoutBeauty.changeTabState(mCurId);
                getBeautyBarView().scrollHorListToStart();
                getBeautyBarView().statisticItemShow(mBeautyBarView.getHorizontalBarScrollX());
            }

            if (!mIsNeedGoToBeauty) {
                showInsideBottomBarWithName(R.string.image_edit_beauty, View.NO_ID);
            }
            setConfirmEnable(false);
            if (mOtherBarView != null && SPDataManager.getShowOtherBeautyRedIcon()) {
                SPDataManager.setShowOtherBeautyRedIcon(false);
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_BEAUTY_CLICK);
        } else if (mCurId == R.id.mirror) {
            showInsideBottomBarWithName(R.string.image_edit_other_mirror, View.NO_ID);
            setConfirmEnable(true);
            if (mMirrorBarView != null && mMirrorBarView.getBaseBitmap() != mSrcBitmap.getBitmap()) {//说明两边不一致  需要刷新
                mMirrorBarView.setBaseBitmap(mSrcBitmap.getBitmap(), mImageBean);
            }
            StatisticsUtils.statisticsCustomPreviewClick(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_TOOLS_MIRROR_CLICK);
            mOtherBarView.statisticEditItemClick(mCurId);
        } else if (mCurId == R.id.edit) {
//            mBottomLayoutBeauty.changeTabState(mCurId);
            getEditOperationBar().scrollToStart();
            getEditOperationBar().getItemWidth();
            getEditOperationBar().getBarItemCount();
            getEditOperationBar().statisticItemShow(getEditOperationBar().getHorizontalBarScrollX());
            if (mIsFirstTimeInBeauty) {
                mIsFirstTimeInBeauty = false;
                updateSrcBitmapOfEdit(mSrcBitmap);
            }
            if (!mShowWatermark) {
                setWaterMarkVisible(true);
            }
        } else {
            //do nothing
        }

        if (mCurId == R.id.op_mixer) {
            //在回调中处理mixer
        } else if (mCurId == R.id.edit && getEditOperationBar().getCurSelectBtnId() == R.id.op_mixer) {
            //在回调中处理mixer
        } else {
            showOperationsViewByTabId(mCurId);
            if (mCurId != R.id.adjust || mCurId != R.id.filter) {
                refreshBitmap();
            }

            if (!mIsNeedGoToBeauty || mCurId == R.id.filter || mCurId == R.id.sticker) {
                if (mIsNeedGoToBeauty) {
                    //切换到filter或addemoji中，并保持topView显示
                    showCoverContent();
                } else {
                    //隐藏topView，并切换到指定模块中
                    hideTopView();
                }
                doShowOperationBarAnim();

            } else {
                //doImageContentAnim(true);
                mImageContent.setVisibility(View.INVISIBLE);
                mCoverImageView.setVisibility(View.VISIBLE);
                updateBottomTabSelectStatus(mCurId);
            }
        }
//        DLog.d("fLog", "visible " + (mAddEmojiView.getVisibility() == View.VISIBLE));
    }

    private void resetFromLastModule(int lastId) {
        if (lastId == R.id.sticker) {
            if (mAddEmojiView != null && mAddEmojiView.getEmojiPanelButNotInit() != null) {
                mAddEmojiView.setEmojiPanelVisible(false, false);
                mAddEmojiView.restore(false);
            }
            mCanvasEditEmojiView.reset();
            mFilterCallBackListener.cancel();
        } else if (lastId == R.id.filter) {
            mFilterView.reset();
            mFilterCallBackListener.cancel();
        }
    }


    /**
     * 设置GpuImageView的宽高
     */
    public void resetGPUImageView() {
        mImageView.post(new Runnable() {

            @Override
            public void run() {
                float[] size = getCurrentSize(mImageView);
                if (size[0] == 0.0f || size[1] == 0.0f) {
                    initGPUImageView();
                } else {
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAdjustGPUImageView.getLayoutParams();
                    params.width = (int) size[0];
                    params.height = (int) size[1];
                    params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
                    mAdjustGPUImageView.setLayoutParams(params);
                    updateCoverImageViewLayout((int) size[0], (int) size[1]);
                    mImageEraserView.updateContentRect((int) size[0], (int) size[1]);
                    mImageMixerView.updateBottomRect((int) size[0], (int) size[1]);

//                    mEyeDecorationView.updateBottomRect((int)size[0], (int)size[1]);
                }
            }
        });
    }

    /**
     * 设置GpuImageView的宽高
     */
    public void resetGPUImageView(final int bitmapSize[]) {
        int vw = mImageView.getWidth();
        int vh = mImageView.getHeight();
        if (vw == 0 || vh == 0) {
            vw = mAdjustGPUImageView.getWidth();
            vh = mAdjustGPUImageView.getHeight();
        }
        int trueW, trueH;
        int bw = bitmapSize[0], bh = bitmapSize[1];
        if (bw * 1.0f / bh >= vw * 1.0f / vh) {//比较宽
            trueW = vw;
            trueH = (int) (trueW * 1.0f / bw * bh + 0.5f);
        } else {//比较高
            trueH = vh;
            trueW = (int) (trueH * 1.0f / bh * bw + 0.5f);
        }
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAdjustGPUImageView.getLayoutParams();
        params.width = trueW;
        params.height = trueH;
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mAdjustGPUImageView.setLayoutParams(params);
        updateCoverImageViewLayout(trueW, trueH);
        mImageEraserView.updateContentRect(trueW, trueH);
        mImageMixerView.updateBottomRect(trueW, trueH);

//        mEyeDecorationView.updateBottomRect(trueW, trueH);
    }

    //初始化相框大小
    private void initFrameView() {
        Resources res = getResources();
        int bw = mSrcBitmap.getBitmap().getWidth();
        int bh = mSrcBitmap.getBitmap().getHeight();
        int vw = ImageHelper.SCREEN_WIDTH - res.getDimensionPixelSize(R.dimen.image_edit_margin_left) * 2;
        int vh = ImageHelper.SCREEN_HEIGHT - res.getDimensionPixelSize(R.dimen.image_edit_margin_top) * 2 -
                res.getDimensionPixelSize(R.dimen.image_edit_bottom_bar_height) - res.getDimensionPixelSize(R.dimen.image_eidt_top_height);
        if (bw * 1.0f / bh >= vw * 1.0f / vh) {//比较宽,为了让图完整显示,只能等比缩放高度
            trueW = vw;
            trueH = (int) (trueW * 1.0f / bw * bh + 0.5f) + 1;
        } else {//比较高
            trueH = vh;
            trueW = (int) (trueH * 1.0f / bh * bw + 0.5f) + 1;
        }
        ViewGroup.LayoutParams params = mFrameView.getLayoutParams();
        params.width = trueW;
        params.height = trueH;
        mFrameView.setLayoutParams(params);
    }

    /**
     * 第一次初始化
     */
    private void initGPUImageView() {
        Resources res = getResources();
        int bw = mSrcBitmap.getBitmap().getWidth();
        int bh = mSrcBitmap.getBitmap().getHeight();
        int vw = ImageHelper.SCREEN_WIDTH - res.getDimensionPixelSize(R.dimen.image_edit_margin_left) * 2;
        int vh;
        if (!mIsNeedGoToBeauty) {
            vh = ImageHelper.SCREEN_HEIGHT - res.getDimensionPixelSize(R.dimen.image_edit_margin_top) * 2 -
                    res.getDimensionPixelSize(R.dimen.image_edit_bottom_bar_height) - res.getDimensionPixelSize(R.dimen.image_eidt_top_height) - DeviceUtils.dip2px(50);
        } else {
            vh = ImageHelper.SCREEN_HEIGHT - res.getDimensionPixelSize(R.dimen.image_edit_margin_top) * 2 -
                    res.getDimensionPixelSize(R.dimen.image_edit_bottom_bar_height) - res.getDimensionPixelSize(R.dimen.image_eidt_bottom_height) - getResources().getDimensionPixelSize(R.dimen.image_eidt_select_bar_height);
        }
        //int vh = ImageHelper.SCREEN_HEIGHT - res.getDimensionPixelSize(R.dimen.image_edit_bottom_bar_height) - res.getDimensionPixelSize(R.dimen.image_edit_bottom_button_size);
        int trueW, trueH;
        if (bw * 1.0f / bh >= vw * 1.0f / vh) {//比较宽
            trueW = vw;
            trueH = (int) (trueW * 1.0f / bw * bh + 0.5f);
        } else {//比较高
            trueH = vh;
            trueW = (int) (trueH * 1.0f / bh * bw + 0.5f);
        }
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAdjustGPUImageView.getLayoutParams();
        params.width = trueW;
        params.height = trueH;
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mAdjustGPUImageView.setLayoutParams(params);

        updateCoverImageViewLayout(trueW, trueH);

        mImageEraserView.updateContentRect(trueW, trueH);
        mImageMixerView.updateBottomRect(trueW, trueH);

//        mEyeDecorationView.updateBottomRect(trueW, trueH);
    }


    private void updateCoverImageViewLayout(int width, int height) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mCoverImageView.getLayoutParams();
        params.width = width;
        params.height = height;
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mCoverImageView.setLayoutParams(params);
    }

    /**
     * 设置保存按钮的状态Enable 或者 unenable
     */
    private void setSaveBtEnable(boolean enable) {
        if (enable) {
            mSaveBt.setEnabled(true);
            mSaveBt.setTextColor(getResources().getColor(R.color.accent_color));
        } else {
            mSaveBt.setEnabled(false);
            mSaveBt.setTextColor(getResources().getColor(R.color.accent_color_selector));
        }
    }

    /**
     * 设置应用按钮是否能点击
     *
     * @param flag
     */
    public void setConfirmEnable(boolean flag) {
        if (mBottomLayoutInSide != null) {
            mBottomLayoutInSide.setConfirmEnable(flag);
        }
    }

    /**
     * 底部动画
     *
     * @param outSide
     */
    public void showBottomBar(boolean outSide, int type) {
        if (mBottomLayoutInSide == null) {
            initBottomLayoutInSide();
        }
        if (outSide && mBottomLayoutOutSide.getVisibility() == View.GONE) {
            mBottomLayoutOutSide.setVisibility(View.VISIBLE);
            mBottomLayoutInSide.setVisibility(View.GONE);
            mBottomLayoutOutSide.startAnimation(getBottomIn());
            mBottomLayoutInSide.startAnimation(getTopOut());
        } else if (!outSide && mBottomLayoutInSide.getVisibility() == View.GONE) {
            mBottomLayoutInSide.setType(type);
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mBottomLayoutOutSide.setVisibility(View.GONE);
            mBottomLayoutOutSide.startAnimation(getBottomOut());
            mBottomLayoutInSide.startAnimation(getTopIn());
        } else if (!outSide) {
            mBottomLayoutInSide.setType(type);
        }

        if (outSide) {
            setWaterMarkVisible(true);
        } else {//如果点击的是watermark自己 则不需要隐藏
            if (mCurId != R.id.watermark) {
                setWaterMarkVisible(false);
            }
        }
    }

    /**
     * 底部变成mBottomLayoutInSide 中间显示名称
     *
     * @param name
     */
    public void showInsideBottomBarWithName(String name) {
        if (mBottomLayoutInSide == null) {
            initBottomLayoutInSide();
        }
        mBottomLayoutInSide.setNameText(name);
        mBottomLayoutInSide.setType(TYPE_NAME);
        //showBottomBar(false, BottomInsideBarView.TYPE_NAME);
    }

    /**
     * 底部变成mBottomLayoutInSide 中间显示名称
     *
     * @param resId
     */
    public void showInsideBottomBarWithName(int resId, int drawableId) {
        if (mBottomLayoutInSide == null) {
            initBottomLayoutInSide();
        }
        mBottomLayoutInSide.setNameText(resId, drawableId);
        mBottomLayoutInSide.setType(TYPE_NAME);
//        showBottomBar(false, BottomInsideBarView.TYPE_NAME);
    }

//    public void showInsideBottomBarWithButton() {
//        if (mBottomLayoutInSide == null) {
//            initBottomLayoutInSide();
//        }
//        mBottomLayoutInSide.setNameText(R.string.image_edit_sticker, R.drawable.ic_tool_help);
//        mBottomLayoutInSide.setType(TYPE_BUTTON);
//        //showBottomBar(false, BottomInsideBarView.TYPE_BUTTON);
//    }

    /**
     * 底部变成mBottomLayoutInSide 中间进度条
     * 这个用于滤镜  滤镜的进度条根据传入的颜色来确认
     *
     * @param progress
     * @param color
     */
    public void showInsideBottomBarWithProgress(int progress, int color) {
        if (mBottomLayoutInSide == null) {
            initBottomLayoutInSide();
        }
        mBottomLayoutInSide.setProgress(progress);
        mBottomLayoutInSide.setType(BottomInsideBarView.TYPE_PROGRESS);
    }

    /**
     * 底部变成mBottomLayoutInSide 中间进度条
     * 这个用于调整  调整的进度条用默认颜色的
     *
     * @param progress
     */
    public void showInsideBottomBarWithProgress(int progress) {
        if (mBottomLayoutInSide == null) {
            initBottomLayoutInSide();
        }
//        mBottomLayoutInSide.setSeekBarDefaultColor();
//        setDefaultProgressTvBgColor(getResources().getColor(R.color.accent_color));
        mBottomLayoutInSide.setProgress(progress);
        mBottomLayoutInSide.setType(BottomInsideBarView.TYPE_PROGRESS);
        //showBottomBar(false, BottomInsideBarView.TYPE_PROGRESS);
    }

    /**
     * 获取当前进度条的进度值
     *
     * @return
     */
    public int getSeekBarProgress() {
        return mBottomLayoutInSide.getProgress();
    }

    @Override
    public void setFilter(GPUImageFilter filter) {
        if (mAdjustGPUImageView != null) {
            mAdjustGPUImageView.setFilter(filter);
        }
        if (mImageViewCover != null && filter.getClass() != GPUImageFilter.class) {
            mImageViewCover.setVisibility(View.INVISIBLE);
            mImageViewCover.setImageBitmap(null);
        }
        checkVipRes(false);
    }

    @Override
    public void setArtFilter(FilterBean bean) {

    }

    @Override
    public void requestDraw(float process) {

    }

    @Override
    public void clearFilter(GPUImageFilter filter) {

    }

    @Override
    public void requestRender() {
        if (mAdjustGPUImageView != null) {
            mAdjustGPUImageView.requestRender();
        }
    }

    /**
     * 初始化BottomLayoutInSide
     */
    private void initBottomLayoutInSide() {
        ViewStub stub = (ViewStub) findViewById(R.id.bottom_layout_inside_stub);
        mBottomLayoutInSide = (BottomInsideBarView) stub.inflate();
        mSeekBarChangeListener = new com.photoeditor.demo.ui.widget.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(CustomNumSeekBar seekBar) {
                mEditOperationViewContainer.startAnimation(getAlphaIn());
                mEditOperationViewContainer.setVisibility(View.VISIBLE);
                mProgressLayout.setVisibility(View.GONE);
            }

            @Override
            public void onStartTrackingTouch(CustomNumSeekBar seekBar) {
                mEditOperationViewContainer.startAnimation(getAlphaOut());
                mEditOperationViewContainer.setVisibility(View.GONE);
                mProgressLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onProgressChanged(CustomNumSeekBar seekBar, int progress,
                                          boolean fromUser) {
                mProgressTv.setText(progress + "");
                if (fromUser) {
                    if (mCurId == R.id.filter) {
                        mFilterView.onProgressChange(progress);
                    } else if (mCurId == R.id.adjust) {
                        mAdjustBarView.onProgressChange(progress);
                    } else if (mCurId == R.id.tilt_shift) {
                        mTileShiftView.onProgressChange(progress);
                    } else if (mCurId == R.id.edit) {
                        getEditOperationBar().onProgressChanged(progress);
                    }
                }
            }
        };
        mBottomLayoutInSide.setOnProgressChangeListener(mSeekBarChangeListener);
        mBottomLayoutInSide.setOnClickListener(this);
        mBottomLayoutInSide.setActivity(EditorImageActivity.this);
    }

    public Animation getBottomIn() {
        if (mBottomLayoutBottomIn == null) {
            mBottomLayoutBottomIn = AnimationUtils.loadAnimation(this, R.anim.bottom_in);
        } else {
            mBottomLayoutBottomIn.reset();
        }
        return mBottomLayoutBottomIn;
    }

    public Animation getBottomInUpToDown() {
        if (mBottomLayoutBottomInUpToDown == null) {
            mBottomLayoutBottomInUpToDown = AnimationUtils.loadAnimation(this, R.anim.bottom_in_up_to_down);
        } else {
            mBottomLayoutBottomInUpToDown.reset();
        }
        return mBottomLayoutBottomInUpToDown;
    }

    public Animation getBottomOut() {
        if (mBottomLayoutBottomOut == null) {
            mBottomLayoutBottomOut = AnimationUtils.loadAnimation(this, R.anim.bottom_out);
        } else {
            mBottomLayoutBottomOut.reset();
        }
        return mBottomLayoutBottomOut;
    }

    public Animation getTopIn() {
        if (mBottomLayoutTopIn == null) {
            mBottomLayoutTopIn = AnimationUtils.loadAnimation(this, R.anim.top_in);
        } else {
            mBottomLayoutTopIn.reset();
        }
        return mBottomLayoutTopIn;
    }

    public Animation getTopOut() {
        if (mBottomLayoutTopOut == null) {
            mBottomLayoutTopOut = AnimationUtils.loadAnimation(this, R.anim.top_out);
        } else {
            mBottomLayoutTopOut.reset();
        }
        return mBottomLayoutTopOut;
    }

    public Animation getAlphaIn() {
        if (mAlphaIn == null) {
            mAlphaIn = new AlphaAnimation(0f, 1f);
            mAlphaIn.setDuration(180);
        } else {
            mAlphaIn.reset();
        }
        return mAlphaIn;
    }

    public Animation getAlphaOut() {
        if (mAlphaOut == null) {
            mAlphaOut = new AlphaAnimation(1f, 0f);
            mAlphaOut.setDuration(180);
        } else {
            mAlphaOut.reset();
        }
        return mAlphaOut;
    }

    /**
     * 下面是水印相关
     */
    private void initWaterMark() {
        mWaterMarkLayout = (RelativeLayout) findViewById(R.id.watermark_layout);
        mWaterMarkIV = (ImageView) findViewById(R.id.iv_watermark);
        Watermark watermark = mWatermarkManager.getCurrentWatermark();
        if (mWatermarkManager.isPlaceholderWatermark(watermark)) {//没有水印
            mWaterMarkIV.setImageBitmap(null);
        } else {
            Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
            if (bitmap != null) {
                mWaterMarkIV.setImageBitmap(bitmap);
            }
        }
        mCoverImageView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {

            @Override
            public void onLayoutChange(View v, int left, int top, int right,
                                       int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                refreshWaterMark();
                mCoverImageView.removeOnLayoutChangeListener(this);
            }
        });

//	    mWaterMarkLayout.setOnClickListener(this);
    }

    /**
     * 刷新水印
     */
    public void refreshWaterMark() {
        mCoverImageView.post(new Runnable() {

            @Override
            public void run() {
                if (mSrcBitmap != null && mWaterMarkLayout != null && mShowWatermark) {
                    //水印View的父View是mImageView的父View
                    setWaterMarkPosition(ImageRectUtils.getViewRect(mCoverLayout), ImageRectUtils.getViewRect(mCoverImageView));
                    mWaterMarkLayout.setVisibility(View.VISIBLE);
                } else {
                    mWaterMarkLayout.setVisibility(View.GONE);
                }
            }
        });
    }


    /**
     * viewRect是父View的Rect
     *
     * @param viewRect
     * @param drawRect
     */
    public void setWaterMarkPosition(RectF viewRect, RectF drawRect) {
        Watermark watermark = mWatermarkManager.getCurrentWatermark();

        RectF waterMarkRect = BitmapUtils.getWaterMarkRect(this, drawRect, watermark);

        int padding = DeviceUtils.dip2px(this, 5);

        float left = waterMarkRect.left - padding;
        if (left < drawRect.left) {
            left = drawRect.left;
        }
        float top = waterMarkRect.top - padding;
        if (top < drawRect.top) {
            top = drawRect.top;
        }
        float right = waterMarkRect.right + padding;
        if (right > drawRect.right) {
            right = drawRect.right;
        }
        float bottom = waterMarkRect.bottom + padding;
        if (bottom > drawRect.bottom) {
            bottom = drawRect.bottom;
        }
        RectF waterMarkLayoutRect = new RectF(left, top, right, bottom);

        RelativeLayout.LayoutParams layoutLp = (RelativeLayout.LayoutParams) mWaterMarkLayout.getLayoutParams();
        int width = (int) (waterMarkLayoutRect.width() + 0.5f);
        int height = (int) (waterMarkLayoutRect.height() + 0.5f);
        int topMargin = (int) (waterMarkLayoutRect.top - viewRect.top);
        int leftMargin = (int) (waterMarkLayoutRect.left - viewRect.left);
        if (width != layoutLp.width || height != layoutLp.height || topMargin != layoutLp.topMargin || leftMargin != layoutLp.leftMargin) {
            layoutLp.width = width;
            layoutLp.height = height;
            layoutLp.topMargin = topMargin;
            layoutLp.leftMargin = leftMargin;
            mWaterMarkLayout.setLayoutParams(layoutLp);
        }

        RelativeLayout.LayoutParams ivLp = (RelativeLayout.LayoutParams) mWaterMarkIV.getLayoutParams();
        width = (int) waterMarkRect.width();
        height = (int) waterMarkRect.height();
        leftMargin = (int) (waterMarkRect.left - left);
        topMargin = (int) (waterMarkRect.top - top);
        if (width != ivLp.width || height != ivLp.height || topMargin != ivLp.topMargin || leftMargin != ivLp.leftMargin) {
            ivLp.width = width;
            ivLp.height = height;
            ivLp.topMargin = topMargin;
            ivLp.leftMargin = leftMargin;
            mWaterMarkIV.setLayoutParams(ivLp);
        }
    }

    /**
     * 水印可见或者不可见
     *
     * @param visible
     */
    private void setWaterMarkVisible(final boolean visible) {
        if (visible && mIsNeedGoToBeauty) {
            if (mCurId == R.id.edit) {
                //do nothing
            } else {
                return;
            }
        }
        mShowWatermark = visible;
        refreshWaterMark();
    }

    /**
     * watermark的选择View
     *
     * @return
     */
    public View getWatermarkBarView() {
        if (mWaterMarkBarLayout == null) {
            initWatermarkbarView();
        }
        return mWaterMarkBarLayout;
    }

    private void initWatermarkbarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.watermark_bar_stub);
        mWaterMarkBarLayout = stub.inflate();
        LinearLayout view = (LinearLayout) mWaterMarkBarLayout.findViewById(R.id.watermark_bar_layout);
        initWatermarkBar(view);
    }

    private void initWatermarkBar(LinearLayout view) {
        List<Watermark> watermarkList = mWatermarkManager.getAvailableWatermarks();
        mWaterMarkBarLayout.setBackgroundResource(R.drawable.image_edit_sencond_bg);
        int size = watermarkList.size();
        int width = getResources().getDimensionPixelSize(R.dimen.watermark_width);
        View.OnClickListener onclick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Watermark watermark = (Watermark) v.getTag();
                if (watermark == null) {
                    return;
                }
                mWatermarkManager.setTempWatermark(watermark);
                if (mWatermarkManager.isPlaceholderWatermark(watermark)) {
//                    if(!hasShowWatermarkSVip && !AppVipManager.isVip()) {
//                        hasShowWatermarkSVip = true;
//                        SVipController.getInstance().showPurchaseActivityOfWatermark();
//                    }
                    mWaterMarkIsExist = false;
                    mWaterMarkIV.setImageBitmap(null);
                } else {
                    mWaterMarkIsExist = true;
                    Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
                    if (bitmap != null) {
                        mWaterMarkIV.setImageBitmap(bitmap);
                    }
                }
                //refreshWaterMark();
                setWaterMarkPosition(ImageRectUtils.getViewRect((View) mImageView.getParent()), getDrawableRect(mImageView));
            }
        };
        for (int i = 0; i < size; i++) {
            WatermarkSelectView demoView = new WatermarkSelectView(this);
            demoView.setTag(watermarkList.get(i));
            demoView.setBackgroundResource(R.drawable.image_edit_sencond_bg_selector);
            demoView.setOnClickListener(onclick);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, WindowManager.LayoutParams.MATCH_PARENT);
            demoView.setImageResource(watermarkList.get(i).getDemoResId());
            demoView.setWatermarkInfo(mWatermarkManager, watermarkList.get(i));
            view.addView(demoView, lp);
            if (watermarkList.get(i) == mWatermarkManager.getCurrentWatermark()
                    && view instanceof WatermarkLinearLayout) {
                ((WatermarkLinearLayout) view).setSelectView(demoView);
            }
        }
    }

    /**
     * 获取当前显示图片的宽高
     *
     * @return
     */
    public float[] getCurrentSize(AnimationCropImageView view) {
        float result[] = new float[]{0.0f, 0.0f};
        Drawable mDrawable = view.getDrawable();
        if (mDrawable == null) {
            return result;
        }
        Rect r = mDrawable.getBounds();
        //真实宽高
        int w = r.width();
        int h = r.height();
        Matrix matrix1 = view.getImageMatrix();
        float[] values1 = new float[10];
        matrix1.getValues(values1);
        //当前显示的宽高

        result[0] = w * values1[0];
        result[1] = h * values1[4];
        return result;
    }

    /**
     * 获取当前图片显示的Bounds
     *
     * @return Rect
     */
    public RectF getDrawableRect(AnimationCropImageView view) {
        float size[] = getCurrentSize(view);
        float viewWidth = view.getWidth();
        float Viewheight = view.getHeight();

        int bLeft, bTop;
        int vLeft, vTop;
        int location[] = new int[2];
        view.getLocationInWindow(location);
        vLeft = location[0];
        vTop = location[1];

        float widthDistance, heightDistance;
        widthDistance = (viewWidth - size[0]) / 2;
        heightDistance = (Viewheight - size[1]) / 2;
        bLeft = (int) (vLeft + widthDistance + 0.5);
        bTop = (int) (vTop + heightDistance + 0.5);

        return new RectF(bLeft, bTop, (int) (bLeft + size[0] + 0.5f), (int) (bTop + size[1] + 0.5f));
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            /*if (mCurId == R.id.addemoji) {
                if (mAddEmojiView != null && mAddEmojiView.getEmojiPanelButNotInit() != null && mAddEmojiView.getEmojiPanelButNotInit().getVisibility() == View.VISIBLE) {
                    mAddEmojiView.setEmojiPanelVisible(false, true);
                    mAddEmojiView.restore(false);
                    return true;
                }
            } else */
            if (mCurId == R.id.doodle) {
                if (mDoodleBarView != null) {
                    View bv = mDoodleBarView.getBrushesPopupView();
                    View ev = mDoodleBarView.getEraserPopupView();
                    if (bv != null && bv.getVisibility() == View.VISIBLE) {
                        mDoodleBarView.setBrushesPopupView(View.GONE);
                        return true;
                    } else if (ev != null && ev.getVisibility() == View.VISIBLE) {
                        mDoodleBarView.setEraserPopupView(View.GONE);
                        return true;
                    }
                }
            } else if ((mCurId == R.id.beauty /*|| mCurId == R.id.body*/) && isTipsOn()) {
                dismissGuideView();
                return true;
            }
            if (mNeedSave) {
                showExitAlertDialog();
                return true;
            } else {
                onExit();
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SPDataManager.setArtistEnable(false);
        EventBus.getDefault().unregister(this);
        mOriginalFilePath = null;
//        if (mStickerManager != null) {
//            mStickerManager.destroyNotBitmap();
//        }
        if (mFilterView != null) {//注意 ：如果没有执行setContentView就为空
            mFilterView.onDestory();
        }
        if (mMagazineTempletBar != null) {
            mMagazineTempletBar.onDestory(true);
        }
        if (mFrameBarView != null) {
            mFrameBarView.onDestory(true);
        }

        if (mMirrorView != null) {
            mMirrorView.destory();
        }
        if (mSaveTask != null) {
            mSaveTask.cancel(true);
        }
        if (mStickerViewBg != null && !mStickerViewBg.isRecycled()) {
            mStickerViewBg.recycle();
        }
        if (mBackgroundBitmap != null && !mBackgroundBitmap.isRecycled()) {
            mBackgroundBitmap.recycle();
        }
        if (mAdProvider != null) {
            mAdProvider.destroyAd();
        }
        if (mExitAdProvider != null) {
            mExitAdProvider.destroyAd();
        }
        AsyncTaskDefaultSerialExecutor.getInstance().clearTasks();

        StickerUnlockData.getInstance().clearSticker();
    }

    /**
     * 退出时的Dialog
     */
    private void showExitAlertDialog() {
        if (mExitAlertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(EditorImageActivity.this);
            builder.setNegativeButton(R.string.image_edit_exit_dialog_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mExitAlertDialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.image_edit_exit_dialog_save, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (mIsNeedShare) {
                    }
                    onExit();
                }
            });
            builder.setTitle(R.string.image_edit_exit_dialog_title);
            builder.setMessage(R.string.image_edit_exit_dialog_message);
            mExitAlertDialog = builder.create();
            mExitAlertDialog.setCancelable(true);
            mExitAlertDialog.setCanceledOnTouchOutside(false);
            mExitAlertDialog.show();
            FontUtil.setAlertDialogCustomFont(mExitAlertDialog);
        } else {
            mExitAlertDialog.show();
        }
    }

    /**
     * 获取保存时的AsyncTask
     *
     * @return
     */
    private AsyncTask<String, Integer, Boolean> getSaveTask() {
        AsyncTask<String, Integer, Boolean> mSaveImageTask = new AsyncTask<String, Integer, Boolean>() {
            @Override
            protected void onPreExecute() {
                if (mSaveTaskProgressDialog == null) {
                    mSaveTaskProgressDialog = DialogUtils.showCoverProgressDialog(EditorImageActivity.this);
                } else {
                    mSaveTaskProgressDialog.show();
                }
                getLoadingView().startLoading();
            }

            @Override
            protected Boolean doInBackground(String... params) {
                if (params != null && params.length == 2) {
                    Bitmap bitmap = mSrcBitmap.getBitmap();
                    int quality = 100;
                    if (mIsNeedPublish) {
                        bitmap = BitmapDecoder.scaleBitmapToUpload(bitmap);
                        quality = 90;
                    }
                    if (mWaterMarkIsExist) {
                        bitmap = BitmapUtils.getWaterMarkBitmap(EditorImageActivity.this, bitmap, mWatermarkManager);
                    }
                    mWatermarkManager.saveLastUseWatermark();

                    boolean success;
                    success = ImageHelper.saveBitmapAsJPG(EditorImageActivity.this, bitmap, quality, params[0], params[1], new FolderHelper.OnScanCompletedListener() {

                        @Override
                        public void onScanCompleted(String path, final Uri uri, int orientation) {
                            dealUriBrocast(uri, path);
                        }
                    });
                    return success;
                }
                return false;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                getLoadingView().stopLoading();
                StatisticsUtils.statisticsEditResult(result);
                if (result) {
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_save_success), Toast.LENGTH_SHORT).show();
                    // 编辑成功，保持编辑次数
                    SPDataManager.setEditCount(SPDataManager.getEditCount() + 1);
                } else {//失败了直接Dismiss掉
                    if (mSaveTaskProgressDialog != null && !isFinishing()) {
                        mSaveTaskProgressDialog.dismiss();
                    }
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_save_fail), Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        };

        return mSaveImageTask;
    }

    /**
     * 获取保存时的AsyncTask
     *
     * @return
     */
    private AsyncTask<String, Integer, Boolean> getSaveToTempAndPublishTask() {
        AsyncTask<String, Integer, Boolean> mSaveImageTask = new AsyncTask<String, Integer, Boolean>() {
            private String mFileName;
            private String mDirPath;

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected Boolean doInBackground(String... params) {
                mFileName = "temp_publish.jpg";
                mDirPath = FolderHelper.getOrCreateEditCachePath(EditorImageActivity.this).getAbsolutePath();
                Bitmap bitmap = mSrcBitmap.getBitmap();
                if (mIsNeedPublish) {
                    bitmap = BitmapDecoder.scaleBitmapToUpload(bitmap);
                }
                if (mWaterMarkIsExist) {
                    bitmap = BitmapUtils.getWaterMarkBitmap(EditorImageActivity.this, bitmap, mWatermarkManager);
                }
                boolean success = ImageHelper.saveBitmapAsJPGWithoutInsertDb(EditorImageActivity.this, bitmap, mDirPath, mFileName);
                return success;
            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (result) {
                    ConfirmUploadActivity.startConfirmUploadActivity(EditorImageActivity.this, mDirPath + "/" + mFileName, getIntent().getIntExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, 0));
                } else {//失败了直接Dismiss掉
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.image_edit_save_fail), Toast.LENGTH_SHORT).show();
                }
                finish();
            }
        };

        return mSaveImageTask;
    }

    private void dealUriBrocast(final Uri u, final String path) {
        TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
            @Override
            public void run() {
                statisticsSave();
                try {
                    mSaveTaskProgressDialog.dismiss();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                if (mIsNeedShare) {
                    return;
                } else if (mIsNeedPublish) {
                    ConfirmUploadActivity.startConfirmUploadActivity(EditorImageActivity.this, path, getIntent().getIntExtra(ActionConstant.Extras.EXTRA_TOPIC_ID, 0));
                    finish();
                    return;
                }
                Bundle bundle = null;
                if (mUseEffectInfo != null) {
//                    bundle = RateGuide.newBundle(mOriginalFilePath,
//                            MediaTypeUtil.TYPE_OTHER_IMAGE,
//                            path,
//                            MediaTypeUtil.TYPE_OTHER_IMAGE,
//                            mUseEffectInfo);
                }

                Intent i = new Intent();
                i.setData(u);
                if (bundle != null) {
                    i.putExtra(RateGuide.INTENT_RATE_EFFECT_BUNDLE, bundle);
                }
                setResult(RESULT_OK, i);

                if (mIsFromOthers || mIsNeedStartPreview || mIsNeedGoToEmojiBar || mIsNeedGoToBeauty || mNeedToApplyFilter) {
                    SpUtils.obtain().save(SpConstant.IS_NEED_TO_SAVE, mNeedSave);
                    ImagePreviewActivity.startPictureViewActivityAndStartShare(EditorImageActivity.this, u, bundle, mMainButtonEntrance, getEntranceForStatistic());
                    finish();
                } else {
                    finish();
                }
            }
        };
        onSave(taskRunnable);
    }

    private int getEntranceForStatistic() {
//        switch (tabId) {
//            case R.id.filter:
//                return DialogStatistic.RateWhere.TYPE_ID_FILTER;
//            case R.id.mirror:
//                return DialogStatistic.RateWhere.TYPE_ID_MIRROR;
//            case R.id.watermark:
//                return DialogStatistic.RateWhere.TYPE_ID_WATERMARK;
//            case R.id.beauty:
//                return DialogStatistic.RateWhere.TYPE_ID_BEAUTY;
//            case R.id.addtext:
//                return DialogStatistic.RateWhere.TYPE_ID_ADJUST;
//            case R.id.op_mixer:
//                return DialogStatistic.RateWhere.TYPE_ID_MIXER;
//            case R.id.tilt_shift:
//                return DialogStatistic.RateWhere.TYPE_ID_BLUR;
//            case R.id.adjust:
//                return DialogStatistic.RateWhere.TYPE_ID_ADJUST;
//            case R.id.crop:
//                return DialogStatistic.RateWhere.TYPE_ID_CROP;
//            case R.id.rotate:
//                return DialogStatistic.RateWhere.TYPE_ID_ROTATE;
//            default:
//                return DialogStatistic.RateWhere.TYPE_DEFAULT;
//        }
        return DialogStatistic.RateWhere.TYPE_ID_EDIT;
    }

    /**
     * 刷新底部tab的选中状态
     */
    private void updateBottomTabSelectStatus(final int tab_id) {
        if (tab_id == R.id.doodle) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.VISIBLE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
//        } else if(mCurId == R.id.op_eraser) {
//            mCanvasEditTextView.setVisibility(View.GONE);
//            mCanvasEditEmojiView.setVisibility(View.GONE);
//            mImageView.setVisibility(View.GONE);
//            mGraffitoView.setVisibility(View.GONE);
//            mAdjustGPUImageView.setVisibility(View.GONE);
//            mRotationImagView.setVisibility(View.GONE);
//            mMirrorView.setVisibility(View.GONE);
//            mFrameView.setVisibility(View.GONE);
//            mMagazineView.setVisibility(View.GONE);
//            mImageEraserView.setVisibility(View.VISIBLE);
//            mImageMixerView.setVisibility(View.GONE);
        } else if (mCurId == R.id.op_mixer) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.tilt_shift) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.VISIBLE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        } else if (tab_id == R.id.addtext) {
            mCanvasEditTextView.setVisibility(View.VISIBLE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        } else if (tab_id == R.id.sticker) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.VISIBLE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        } else if (tab_id == R.id.crop) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.VISIBLE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        } else if (tab_id == R.id.rotate) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.VISIBLE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
            if (mRotateBarView != null) {
                mRotateBarView.restore();
            }
        } else if (tab_id == R.id.beauty /*|| tab_id == R.id.body*/) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
        } else if (tab_id == R.id.mirror) {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.GONE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.GONE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.VISIBLE);
            ArrayList<BitmapBean> list = new ArrayList<>(1);
            list.add(mImageBean);
            mMirrorView.setSourceBitmapBeans(list);
            mMirrorView.setTemplet(MirrorTempletConstant.mirrorTemplet.get(0));
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        } else if (tab_id == R.id.edit) {
            getEditOperationBar().updateBottomTabSelectStatus();
        } else {
            mCanvasEditTextView.setVisibility(View.GONE);
            mCanvasEditEmojiView.setVisibility(View.GONE);
            mImageView.setVisibility(View.VISIBLE);
            mGraffitoView.setVisibility(View.GONE);
            mAdjustGPUImageView.setVisibility(View.VISIBLE);
            mRotationImagView.setVisibility(View.GONE);
            mMirrorView.setVisibility(View.GONE);
            mFrameView.setVisibility(View.GONE);
            mMagazineView.setVisibility(View.GONE);
            mImageEraserView.setVisibility(View.GONE);
            mImageMixerView.setVisibility(View.GONE);
        }

        if (tab_id == R.id.crop) {
            mImageView.setCropOverlayViewVisibility(View.VISIBLE);
        } else {
            if (tab_id != R.id.edit) {
                mImageView.setCropOverlayViewVisibility(View.GONE);
            }
        }

    }

    /**
     * 刷新当前的图片
     */
    private void refreshBitmap() {
        if (mCurId == R.id.doodle) {
            mGraffitoView.setExtraBitmap(mSrcBitmap.getBitmap(), true);
            if (mDoodleBarView != null) {
                mGraffitoView.reset(mDoodleBarView.getMosaicType());
            }
//        } else if(mCurId == R.id.op_eraser) {
//            mImageEraserView.setSrcBitmap(mSrcBitmap.getBitmap());
        } else if (mCurId == R.id.op_mixer) {

        } else if (mCurId == R.id.adjust || mCurId == R.id.tilt_shift || mCurId == R.id.filter) {
            mAdjustGPUImageView.getGPUImage().deleteImage();
            if (mSrcBitmap != null && mSrcBitmap.getBitmap() != null && !mSrcBitmap.getBitmap().isRecycled()) {
                mAdjustGPUImageView.setImage(mSrcBitmap.getBitmap());
                mSrcBitmapCopy = mSrcBitmap.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
            }
        } else if (mCurId == R.id.beauty /*|| mCurId == R.id.body*/) {
            mBeautyBarView.setSrcBitmap(mSrcBitmap.getBitmap());
        } else if (mCurId == R.id.addtext) {
            mCanvasEditTextView.setImageDrawable(mSrcBitmap);
        } else if (mCurId == R.id.sticker) {
            mCanvasEditEmojiView.setImageDrawable(mSrcBitmap);
        } else if (mCurId == R.id.rotate) {
            mRotationImagView.setImageDrawable(mSrcBitmap);
        } else if (mCurId == R.id.mirror) {
            mMirrorView.setSourceBitmaps(mSrcBitmap.getBitmap());
            ArrayList<BitmapBean> list = new ArrayList<BitmapBean>(1);
            list.add(mImageBean);
            mMirrorView.setSourceBitmapBeans(list);
        } else {
            mAdjustGPUImageView.getGPUImage().deleteImage();
            if (mSrcBitmap != null && mSrcBitmap.getBitmap() != null && !mSrcBitmap.getBitmap().isRecycled()) {
                mSrcBitmapCopy = mSrcBitmap.getBitmap().copy(Bitmap.Config.ARGB_8888, true);
                mAdjustGPUImageView.setImage(mSrcBitmap.getBitmap());
            }
        }
    }

    private Bitmap mSrcBitmapCopy;


    /**
     * 显示对应tabid的操作视图
     *
     * @param tab_id
     */
    public void showOperationsViewByTabId(int tab_id) {

        int childcount = mEditOperationViewContainer.getChildCount();
        for (int index = 0; index < childcount; index++) {
            View childView = mEditOperationViewContainer.getChildAt(index);
            childView.setVisibility(View.GONE);
        }

        if(tab_id == R.id.sticker) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        } else
        {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        }

        if (tab_id == R.id.crop) {
            getCropBarView().setVisibility(View.VISIBLE);
            mImageView.setCropOverlayViewVisibility(View.VISIBLE);
        } else if (tab_id == R.id.rotate) {
            getRotatebarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.filter) {
            if (mFilterView != null) {
                mFilterView.reset();
            }
            mFilterView.setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.adjust) {
            getAdjustBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.doodle) {
            getDoodleBarView().setVisibility(View.VISIBLE);
//        } else if(mCurId == R.id.op_eraser) {
//            getEraserBar().setVisibility(View.VISIBLE);
        } else if (mCurId == R.id.op_mixer) {
            getEraserBar().setVisibility(View.GONE);
            getMixerBar().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.addtext) {
            getAddTextBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.sticker) {
            boolean show = SPDataManager.hasUseSticker();
            View addEmojiBarView = getAddEmojiBarView();
            if(show) {
                addEmojiBarView.setVisibility(View.VISIBLE);
            }
        } else if (tab_id == R.id.watermark) {
            getWatermarkBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.tilt_shift) {
            getTiltShiftBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.beauty /*|| tab_id == R.id.body*/) {
            getBeautyBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.mirror) {
            getMirrorBarView().setVisibility(View.VISIBLE);
        } else if (tab_id == R.id.edit) {
            getEditOperationBar().setVisibility(View.VISIBLE);
        }
        if (tab_id != NO_ID) {
            tabId = tab_id;
        }
    }

    private FrameBarView getFrameBarView() {
        if (mFrameBarView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.frame_bar_stub);
            mFrameBarView = (FrameBarView) stub.inflate();
            mFrameBarView.init(mFrameChangListener);
//			mFrameBarView.setBaseBitmap(getSrcBitmap());
        }
        return mFrameBarView;
    }

    public AdjustBarView getAdjustBarView() {
        if (mAdjustBarView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.adjust_bar_stub);
            mAdjustBarView = (AdjustBarView) stub.inflate();
            mAdjustBarView.setmAdjustGPUImageView(mAdjustGPUImageView);
            mAdjustBarView.init();
        }
        return mAdjustBarView;
    }

    public DoodleBarView getDoodleBarView() {
        if (mDoodleBarView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.doodle_bar_stub);
            mDoodleBarView = (DoodleBarView) stub.inflate();
            mDoodleBarView.setGraffitoView(mGraffitoView);
            mDoodleBarView.setDoodleBarViewListener(new DoodleBarView.DoodleBarViewListener() {
                @Override
                public void doDraw(boolean yes) {
                    setConfirmEnable(yes);
                }
            });
            mDoodleBarView.init();
        }
        return mDoodleBarView;
    }


    private void initRotatebarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.rotate_bar_stub);
        mRotateBarView = (RotateBarView) stub.inflate();
        mRotateBarView.setRotationImageView(mRotationImagView);
        mRotateBarView.init();
    }

    public RotateBarView getRotatebarView() {
        if (mRotateBarView == null) {
            initRotatebarView();
        }
        return mRotateBarView;
    }


    private void initCropbarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.crop_bar_stub);
        mCropBarView = (CropBarView) stub.inflate();
        mCropBarView.setAnimationCropImageView(mImageView);
        mCropBarView.init();
    }

    public View getCropBarView() {
        if (mCropBarView == null) {
            initCropbarView();
        }
        return mCropBarView;
    }

    /**
     * 下面是Emoji相关部分
     */

    private View getAddEmojiBarView() {
        if (mAddEmojiView == null) {
            initAddEmojibarView();
        }
        return mAddEmojiView;
    }

    private int flag = 0;
    class FirstRefreshEmojiHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    flag++;
                    if (mAddEmojiView != null) {
                        mAddEmojiView.reloadData();
                    }
                    break;
                case 1:
                    flag++;
                    break;
                default:
                    break;
            }
            if (flag == 2) {
                if (mAddEmojiView != null) {
                    mAddEmojiView.reloadData();
                }
            }
        }
    }

    /**
     * 初始化时这个顺序不能改变
     */
    private void initAddEmojibarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.addemoji_bar_stub);
        mAddEmojiView = (EmojiBarView) stub.inflate();
        mAddEmojiView.setManager(mStickerManager);
        mAddEmojiView.setStickerBackground(mStickerViewBg);
        mAddEmojiView.setSelectPakName(getStickerPkgName());
        mAddEmojiView.setGifTitle(getGifTitle());
        if (mGifAutoScrollPosition != -1) {
            mAddEmojiView.setGifAutoScrollPosition(mGifAutoScrollPosition);
            mGifAutoScrollPosition = -1;
        }
        if (mStickerAutoScrollPosition != -1) {
            mAddEmojiView.setStickerAutoScrollPosition(mStickerAutoScrollPosition);
            mStickerAutoScrollPosition = -1;
        }
        mAddEmojiView.setStickerViewListener(new StickerView.StickerViewListener() {
            @Override
            public void onStickerViewShow() {
                mCanvasEditEmojiView.setHasPopView(true);
                mIsEmojiPanelShow = true;
            }

            @Override
            public void onStickerViewHide() {
                mCanvasEditEmojiView.setHasPopView(false);
                mIsEmojiPanelShow = false;
            }

            @Override
            public void onStickerItemClick(EmojiBean bean) {
                if(bean.isARType()){
                    float centerX = mCanvasEditEmojiView.getCenterX();
                    float centerY = mCanvasEditEmojiView.getCenterY();
                    if(bean.getARType() == EmojiBean.TYPE_AR_TIME_12){
                        TimeStickerBean timeStickerBean = (TimeStickerBean) bean.getContainerBean();
                        mCanvasEditEmojiView.addCanvasBean(timeStickerBean.deepClone(centerX, centerY));
                    } else if(bean.getARType() == EmojiBean.TYPE_AR_TIME_24){
                        TimeStickerBean timeStickerBean = (TimeStickerBean) bean.getContainerBean();
                        mCanvasEditEmojiView.addCanvasBean(timeStickerBean.deepClone(centerX, centerY));
                    } else if(bean.getARType() == EmojiBean.TYPE_AR_TIME_ELECT){
                        TimeStickerBean timeStickerBean = (TimeStickerBean) bean.getContainerBean();
                        mCanvasEditEmojiView.addCanvasBean(timeStickerBean.deepClone(centerX, centerY));
                    } else if(bean.getARType() == EmojiBean.TYPE_AR_DATE_WEEK){
                        DateStickerBean dateStickerBean = new DateStickerBean(DateStickerBean.TYPE_WEEK);
                        mCanvasEditEmojiView.addCanvasBean(dateStickerBean.deepClone(centerX, centerY));
                    } else if(bean.getARType() == EmojiBean.TYPE_AR_DATE_MONTH){
                        DateStickerBean dateStickerBean = new DateStickerBean(DateStickerBean.TYPE_DATE);
                        mCanvasEditEmojiView.addCanvasBean(dateStickerBean.deepClone(centerX, centerY));
                    } else if(bean.getARType() == EmojiBean.TYPE_AR_LIKE){

                    }
                } else {
                    mCanvasEditEmojiView.addEmoji(bean);
                }
            }

            @Override
            public void onGifClick(String filepath) {
                mCanvasEditEmojiView.addGif(filepath);
            }

            @Override
            public void onMoreClick() {
//                Intent intent = new Intent(EditorImageActivity.this, StoreActivity.class);
//                intent.putExtra(StoreConstant.store.EXTRA_STORE_ENTRANCE, StoreConstant.store.storeEntrance.ENTRANCE_EDIT_STICKER);
//                startActivity(intent);
            }
        });
        mAddEmojiView.init();
        mFirstRefreshEmojiHandler.sendEmptyMessage(0);
    }

    @Subscribe(threadMode = ThreadMode.POSTING, priority = 1)
    public void refreshSticker(final RefreshStickerEvent event) {
        if (event.operation == RefreshStickerEvent.OPERATION_REFRESH_AND_APPLY) {
            EventBus.getDefault().cancelEventDelivery(event);
        }
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                if (mStickerManager == null) {
                    return;
                }
                if (event.operation == RefreshStickerEvent.OPERATION_REFRESH_AND_APPLY) {
                    mCheckedStickerPkgName = event.stickerPkgName;
                    mGifTitle = event.gifTitle;
                    if (!TextUtils.isEmpty(mGifTitle)) {
                        mGifAutoScrollPosition = event.autoSelectPosition;
                    } else {
                        mStickerAutoScrollPosition = event.autoSelectPosition;
                    }
                    if(mCurId != R.id.sticker) {
                        onCancelClick();
                    }
                    onOperationClick(R.id.sticker);
                } else if (event.operation == RefreshStickerEvent.OPERATION_REFRESH_AND_DELETE) {
                    if (mCanvasEditEmojiView != null) {
                        mCanvasEditEmojiView.removeUninstallSticker(event.stickerPkgName);
                    }
                }

                mStickerManager.refreshEmojiData();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSortFilterCategory(final SortFilterCategory event) {
        if (mFilterView != null) {
            mFilterView.onSortFilterCategory(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFilterDownloadBtnClickEventEvent(FilterDownloadBtnClickEvent event) {
        if (mFilterView != null) {
            mFilterView.setCheck2ApplyPosition(event.mPkgName);
            EventBus.getDefault().cancelEventDelivery(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, priority = 1)
    public void onRefreshFilterCategory(final RefreshFilterCategory event) {
        if (TextUtils.isEmpty(event.delCategoryId) && !TextUtils.isEmpty(event.showCategoryId)) {
            // 在这里应用滤镜后，取消后面的接收者接收事件
            if (mCurId != R.id.filter) {
                onCancelClick();
            }
            onOperationClick(R.id.filter);
            EventBus.getDefault().cancelEventDelivery(event);
        }
        postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mFilterView != null) {
                    mFilterView.onRefreshFilterCategory(event);
                }
            }
        }, 400);
    }

    /**
     * 添加文字相关
     */

    public View getAddTextBarView() {
        if (mAddTextView == null) {
            initAddTextbarView();
        }
        return mAddTextView;
    }

    /**
     * 初始化时这个顺序不能改变
     */
    private void initAddTextbarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.addtext_bar_stub);
        mAddTextView = (TextBarView) stub.inflate();
        mAddTextView.setTextBarListener(new TextBarView.TextBarListener() {
            @Override
            public void onTextConfirmed(String text) {
                mCanvasEditTextView.updateText(text);
            }

            @Override
            public void updateColor(int textColor, int bgColor, int checkId, int style) {
                mCanvasEditTextView.updateColor(textColor, bgColor, checkId, style);
            }

            @Override
            public void updateFont(Typeface typeface, String fontKey) {
                mCanvasEditTextView.updateFont(typeface, fontKey);
            }
        });
        mAddTextView.init();
    }


    /**
     * 移轴相关部分
     */
    public TileShiftBarView getTiltShiftBarView() {
        if (mTileShiftView == null) {
            initTiltShiftBarView();
        }
        return mTileShiftView;
    }

    /**
     * 初始化时这个顺序不能改变
     */
    private void initTiltShiftBarView() {
        ViewStub stub = (ViewStub) findViewById(R.id.addtiltshift_bar_stub);
        mTileShiftView = (TileShiftBarView) stub.inflate();
        mTileShiftView.setmAdjustGPUImageView(mAdjustGPUImageView);
        mRadialBlurTipView = (RadialBlurTipView) findViewById(R.id.radial_blur);
        mLinearBlurTipView = (LinearBlurTipView) findViewById(R.id.linear_blur);
        mTileShiftView.setTipView(mRadialBlurTipView, mLinearBlurTipView);
        mTileShiftView.init();
    }

    public Bitmap getSrcBitmap() {
        if (mSrcBitmap != null) {
            return mSrcBitmap.getBitmap();
        } else {
            return null;
        }
    }

    private BeautyBarView getBeautyBarView() {
        if (mBeautyBarView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.beauty_bar_stub);
            mBeautyBarView = (BeautyBarView) stub.inflate();
            mBeautyBarView.setmAdjustGPUImageView(mAdjustGPUImageView);
            mBeautyBarView.setHairColorView(mHairColorView);
            mBeautyBarView.setLipColorView(mLipView);
            mBeautyBarView.setBigEyesView(mBigEyesView);
            mBigEyesView.setProgressDialog(getLoadingView());
            mBeautyBarView.setTailView(mTailView);
            mBeautyBarView.setAnimatorView(getLoadingView(), mLightAnimView);
            mBeautyBarView.setImageViewCover(mImageViewCover);
            mRepairView.setProgressDialog(getLoadingView());
            mBeautyBarView.setReapirView(mRepairView);
            mBeautyBarView.setWhiteTeethView(mWhitenTeethView);
            mBeautyBarView.setMopiView(mMopiBrushView);
            mBeautyBarView.setWhitenView(mWhitenBrushView);
            mBeautyBarView.setBreastView(mBreastView);
            mBeautyBarView.setButtocksView(mButtocksView);
            mBeautyBarView.init();
        }
        return mBeautyBarView;
    }

    private EditOperationView getEditOperationBar() {
        if (mEditOperationBar == null) {
            ViewStub stub = findViewById(R.id.edit_operation_bar);
            mEditOperationBar = (EditOperationView) stub.inflate();
            mEditOperationBar.setActivity(this);
            mEditOperationBar.setSrcBitmap(mSrcBitmap);
            mEditOperationBar.setImageBean(mImageBean);
            mEditOperationBar.setCropImageView(mImageView);
            mEditOperationBar.setAdjustGPUImageView(mAdjustGPUImageView);
            mEditOperationBar.setWatermarkManager(mWatermarkManager);
            mEditOperationBar.setCanvasEditTextView(mCanvasEditTextView);
            mEditOperationBar.setGraffitoView(mGraffitoView);
            mEditOperationBar.setImageMixerView(mImageMixerView);
            mEditOperationBar.setImageEraserView(mImageEraserView);
            mEditOperationBar.setMirrorView(mMirrorView);
            mEditOperationBar.setRotationImageView(mRotationImagView);
            mEditOperationBar.setCanvasEditEmojiView(mCanvasEditEmojiView);
            mEditOperationBar.setHairColorView(mHairColorView);
            mEditOperationBar.setWhitenBrushView(mWhitenBrushView);
            mEditOperationBar.setWhitenTeethView(mWhitenTeethView);
            mEditOperationBar.setLipView(mLipView);
            mEditOperationBar.setBigEyesView(mBigEyesView);
            mEditOperationBar.setRepairView(mRepairView);
            mEditOperationBar.setMopiBrushView(mMopiBrushView);
            mEditOperationBar.setBreastView(mBreastView);
            mEditOperationBar.setButtocksView(mButtocksView);
            mEditOperationBar.setTailView(mTailView);
            mEditOperationBar.init();
        }
        return mEditOperationBar;
    }

    public MirrorBarView getMirrorBarView() {
        if (mMirrorBarView == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.mirror_bar_stub);
            mMirrorBarView = (MirrorBarView) stub.inflate();
            Ratio.RATIO type = Ratio.RATIO.RATIO_1_1;
            mMirrorView.setType(type);
            mMirrorView.setMode(CollageRelativeLayout.MODE_MIRROR);
            mMirrorView.setShareOperation(true);
            mMirrorBarView.init(MirrorTempletConstant.mirrorTemplet, type, mTempletChangeListener);
            mMirrorBarView.setBaseBitmap(getSrcBitmap(), mImageBean);
        }
        return mMirrorBarView;
    }

    private View getMagazineBar() {
        if (mMagazineTempletBar == null) {
            ViewStub stub = (ViewStub) findViewById(R.id.magazine_bar_stub);
            mMagazineTempletBar = (EditMagazineTempletBar) stub.inflate();
            mMagazineTempletBar.setMagazineView(mMagazineView);
//			mMagazineTempletBar.initMagazineData(mIMagazineTempletChangeListener);
            mMagazineTempletBar.init(mIMagazineTempletChangeListener);

        }
        return mMagazineTempletBar;
    }

    private EraserBarView getEraserBar() {
        if (mEraserBarView == null) {
            ViewStub viewStub = findViewById(R.id.eraser_bar_stub);
            mEraserBarView = (EraserBarView) viewStub.inflate();
            mEraserBarView.init();
            mEraserBarView.setEraserView(mImageEraserView);
            mEraserBarView.setActivity(this);
        }

        mEraserBarView.setSettingTopView(getStickerSettingTopView());
        return mEraserBarView;
    }

    public MixerBarView getMixerBar() {
        if (mMixerBarView == null) {
            ViewStub viewStub = findViewById(R.id.mixer_bar_stub);
            mMixerBarView = (MixerBarView) viewStub.inflate();
            mMixerBarView.init();
            mMixerBarView.setMixerView(mImageMixerView);
            mMixerBarView.setActivity(this);
        }
        return mMixerBarView;
    }

    public StickerSettingTopView getStickerSettingTopView() {
        if (mStickerSettingTopView == null) {
            ViewStub stub = findViewById(R.id.sticker_setting_stub_top);
            mStickerSettingTopView = (StickerSettingTopView) stub.inflate();
        }
        return mStickerSettingTopView;
    }

    private LoadingView getLoadingView() {
        if (mLoadingView == null) {
            mLoadingView = (LoadingView) findViewById(R.id.loading_view);
            findViewById(R.id.mask_view).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    return true;
                }
            });
        }
        return mLoadingView;
    }

    public String getCurrentFilterName() {
        if (mFilterView != null) {
            return mFilterView.getCurrentFilterName2();
        } else {
            return ImageFilterTools.FILTER_NAME_DEFAULT;
        }
    }

    private void setProgressTvBgColor(int color) {
        Drawable d = mProgressTv.getBackground();
        d.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        mProgressTv.setBackgroundDrawable(d);
    }

    private void setDefaultProgressTvBgColor(int defalutColor) {
        Drawable d = mProgressTv.getBackground();
        d.clearColorFilter();
        d.setColorFilter(defalutColor, PorterDuff.Mode.SRC_IN);
        mProgressTv.setBackgroundDrawable(d);
    }

    public void initView() {
        int primaryColor = getResources().getColor(R.color.windowBackgroundColor);
        int emphasisColor = getResources().getColor(R.color.accent_color);

        if (mProgressLayout != null) {
            mProgressLayout.setBackgroundResource(R.drawable.image_edit_sencond_bg);
        }

        if (mProgressTv != null) {
            setDefaultProgressTvBgColor(emphasisColor);
        }
    }

    public void onStickerUninstalled(String pkgName, boolean isApk) {
//        super.onStickerUninstalled(pkgName, isApk);
        if (mCanvasEditEmojiView != null) {
            mCanvasEditEmojiView.removeUninstallSticker(pkgName);
        }
        if (mStickerManager != null) {
            mStickerManager.refreshEmojiData();
        }
        if (mAddEmojiView != null) {
            mAddEmojiView.checkEmojiData();
        }
    }

    public void onStickerInstalled(String pkgName, boolean isApk) {
//        super.onStickerInstalled(pkgName, isApk);
        if (mStickerManager != null) {
            mStickerManager.refreshEmojiData();
        }
        if (mAddEmojiView != null) {
            mAddEmojiView.checkEmojiData();
        }
    }


    private void dealFunctionMode() {
    }

    public boolean getLoadEmojiFinish() {
        if (mStickerManager == null) {
            return false;
        } else {
            return mStickerManager.getLoadEmojiFinish();
        }
    }

    public boolean needGoToPkg() {
        return (mIsNeedGoToEmojiBar && !TextUtils.isEmpty(mCheckedStickerPkgName));
    }

    public void setCheckedStickerPkgNameNull() {
        mCheckedStickerPkgName = null;
    }

    public String getStickerPkgName() {
        return mCheckedStickerPkgName;
    }

    public void setGifTitleNull() {
        mGifTitle = null;
    }

    public String getGifTitle() {
        return mGifTitle;
    }

    //引导
    public RelativeLayout showGuideView() {
        mGuideLayout.setVisibility(View.VISIBLE);
        return mGuideLayout;
    }

    public RelativeLayout dismissGuideView() {
        SPDataManager.setEditShowHairColorTip(false);
        mGuideLayout.setVisibility(View.GONE);
        return mGuideLayout;
    }

    public void showLoadingMagazineProgress() {
        mLoadingProgress.setVisibility(View.VISIBLE);
    }

    public void dismissLoadingMagazineProgress() {
        mLoadingProgress.setVisibility(View.GONE);
    }

    public boolean isLoadingMagazineProgressShowing() {
        return mLoadingProgress.getVisibility() == View.VISIBLE;
    }

    public boolean isTipsOn() {
        return (mGuideLayout.getVisibility() == View.VISIBLE);
    }

    //下面的实现展示没有用处
    @Override
    public void showMoveCover(ICollagePathView pathView, float currentX, float currentY, float dx, float dy) {

    }

    @Override
    public void closePopView() {

    }

    @Override
    public void showCollageCover(ICollagePathView pathView, float currentX, float currentY) {

    }

    @Override
    public void moveCollageCover(float currentX, float currentY) {

    }

    @Override
    public void showPopView(ICollagePathView pathView) {

    }

    @Override
    public void closeCollageCoverAndChangBitmap() {

    }

    @Override
    public void closeCollageCover() {

    }

    @Override
    public void showLoading() {
        findViewById(R.id.mask_view).setVisibility(View.VISIBLE);
        getLoadingView().startLoading();
    }

    @Override
    public void hideLoading() {
        getLoadingView().stopLoading();
        findViewById(R.id.mask_view).setVisibility(View.GONE);
    }

    @Override
    public void onClickSetting() {
//        if (mStickerSettingView == null) {
//            ViewStub stub = (ViewStub) findViewById(R.id.sticker_setting_stub);
//            mStickerSettingView = (StickerSettingView) stub.inflate();
//            mStickerSettingView.setEditStickerView(mCanvasEditEmojiView);
//            mStickerSettingView.setStickerSettingListener(new StickerSettingView.StickerSettingListener() {
//                @Override
//                public void onExit() {
//                    getAddEmojiBarView().setVisibility(View.VISIBLE);
//                }
//            });
//
//            mStickerSettingView.setTopView(getStickerSettingTopView());
//        }
//        if (mStickerSettingView.getVisibility() != View.VISIBLE) {
//            mStickerSettingView.setTopView(getStickerSettingTopView());
//            mStickerSettingView.setVisibility(View.VISIBLE);
//
//            getAddEmojiBarView().setVisibility(View.GONE);
//        }
    }

    public void showTopView() {
        if (mTopView.getVisibility() != View.VISIBLE) {
            mTopView.setVisibility(View.VISIBLE);
            mTopView.startAnimation(getTopIn());
            doImageContentAnim(false);
        }
    }

    public void hideTopView() {
        if (mTopView.getVisibility() == View.VISIBLE) {
            mTopView.startAnimation(getTopOut());
            mTopView.setVisibility(View.GONE);
            doImageContentAnim(true);
        }
    }

    public void hideTopForTaller() {
        if (mTopView.getVisibility() == View.VISIBLE) {
            mTopView.startAnimation(getTopOut());
            mTopView.setVisibility(View.GONE);

            if (mCurId != R.id.watermark) {
                setWaterMarkVisible(false);
            }
            imageTransAnimator = ObjectAnimator.ofFloat(mCoverLayout, "translationY", 0, -translateY);
            imageTransAnimator.setInterpolator(new LinearInterpolator());

            imageTransAnimator.setDuration(250);
            if (imageTransAnimator.isRunning()) {
                return;
            }
            imageTransAnimator.start();
            imageTransAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mImageContent.setVisibility(View.VISIBLE);
                    mCoverImageView.setVisibility(View.INVISIBLE);
                    mImageContent.setVisibility(View.VISIBLE);

                    /**
                     * taller开启时，相关view必须关闭
                     */
                    mCanvasEditTextView.setVisibility(View.GONE);
                    mCanvasEditEmojiView.setVisibility(View.GONE);
                    mImageView.setVisibility(View.GONE);
                    mGraffitoView.setVisibility(View.GONE);
                    mAdjustGPUImageView.setVisibility(View.INVISIBLE);
                    mRotationImagView.setVisibility(View.GONE);
                    mMirrorView.setVisibility(View.GONE);
                    mFrameView.setVisibility(View.GONE);
                    mMagazineView.setVisibility(View.GONE);
                    mImageEraserView.setVisibility(View.GONE);

                    if (mCurId == R.id.watermark) {
                        setWaterMarkPosition(ImageRectUtils.getViewRect((View) mImageView.getParent()), getDrawableRect(mImageView));
                    }

                }
            });
        }
    }

    private void showCoverContent() {
        if (mCurId != R.id.watermark) {
            setWaterMarkVisible(false);
        }
        mImageContent.setVisibility(View.INVISIBLE);
        mCoverImageView.setVisibility(View.VISIBLE);
        updateBottomTabSelectStatus(mCurId);
    }

    public static float translateY = ComponentContext.getContext().getResources().getDimension(R.dimen.image_eidt_top_height);

    ObjectAnimator imageTransAnimator;

    public void doImageContentAnim(final boolean up) {
        if (up) {
            if (mCurId != R.id.watermark) {
                if (mCurId == R.id.edit && getEditOperationBar().getCurSelectBtnId() != R.id.watermark) {
                    setWaterMarkVisible(false);
                } else if (mCurId != R.id.edit) {
                    setWaterMarkVisible(false);
                }
            }
            imageTransAnimator = ObjectAnimator.ofFloat(mCoverLayout, "translationY", 0, -translateY);
            imageTransAnimator.setInterpolator(new LinearInterpolator());
        } else {
            if (mImageViewCover.getVisibility() != View.VISIBLE) {
                mCoverImageView.setImageBitmap(mSrcBitmap.getBitmap());
            }
            mImageContent.setVisibility(View.INVISIBLE);
            mCoverImageView.setVisibility(View.VISIBLE);
            imageTransAnimator = ObjectAnimator.ofFloat(mCoverLayout, "translationY", -translateY, 0);
            imageTransAnimator.setInterpolator(new LinearInterpolator());
        }
        imageTransAnimator.setDuration(250);
        if (imageTransAnimator.isRunning()) {
            return;
        }
        imageTransAnimator.start();
        imageTransAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (up) {
                    mImageContent.setVisibility(View.VISIBLE);
                    mCoverImageView.setVisibility(View.INVISIBLE);

                    updateBottomTabSelectStatus(mCurId);

                    if (mCurId == R.id.edit) {
                        if (getEditOperationBar() == null && mCurId == R.id.edit) {
                            // 防止mEditOperationBar为null
                            return;
                        }
                        setWaterMarkPosition(ImageRectUtils.getViewRect((View) mImageView.getParent()), getDrawableRect(mImageView));
                    }
                } else {
                    setWaterMarkVisible(true);
                }
            }
        });
    }

    public void doShowOperationBarAnim() {
        if (mBottomLayoutInSide == null) {
            return;
        }
        /*if (mIsNeedGoToBeauty) {
            if (mCurId != R.id.addemoji && mCurId != R.id.filter) {
                mBottomLayoutInSide.setVisibility(View.VISIBLE);
                hideOperationBar(mCurId);
                mBottomOperationViewContainer.setVisibility(View.VISIBLE);
                mBottomOperationViewContainer.startAnimation(getBottomIn());
            }
        } else */
        {
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mBottomOperationViewContainer.setVisibility(View.VISIBLE);
            mBottomOperationViewContainer.startAnimation(getBottomIn());
        }

        /*if (mIsNeedGoToBeauty){
            if (mCurId == R.id.addemoji || mCurId == R.id.filter) {
                return;
            }
            mBottomLayoutBeauty.startAnimation(getBottomOut());
            mBottomLayoutBeauty.setVisibility(View.GONE);
        }else*/
        {
            mBottomLayoutOutSide.startAnimation(getBottomOut());
            mBottomLayoutOutSide.setVisibility(View.GONE);
        }
    }

//    private void hideOperationBar(int id) {
//        switch (id) {
//            case R.id.edit:
//                getEditOperationBar().startAnimation(getBottomOut());
//                getEditOperationBar().setVisibility(View.GONE);
//                break;
//            case R.id.beauty:
//                break;
//            case R.id.body:
//                break;
//            default:
//        }
//    }

    public void showOperationBarWithAnim(int id) {
        /*if (id == R.id.addemoji) {
            showInsideBottomBarWithButton();
        } else */
        if (id == R.id.filter) {
            if (mBottomLayoutInSide == null) {
                initBottomLayoutInSide();
            }
            mBottomLayoutInSide.setNameText(R.string.image_edit_sticker, R.drawable.ic_tool_help);
            mBottomLayoutInSide.setType(TYPE_BUTTON);
        }
        if (mBottomLayoutInSide.getVisibility() == View.GONE || mBottomLayoutInSide.getVisibility() == View.INVISIBLE) {
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mBottomLayoutInSide.startAnimation(getBottomInUpToDown());
//            mBottomLayoutBeauty.setVisibility(View.GONE);
        }
    }

    public void showOperationBarWithAnim(int id, String name) {
        /*if (id == R.id.addemoji) {
            showInsideBottomBarWithButton();
        } else */
        if (id == R.id.filter) {
            if (mBottomLayoutInSide == null || mBottomLayoutInSide.getType() != BottomInsideBarView.TYPE_NAME) {
                if (mBottomLayoutInSide == null) {
                    initBottomLayoutInSide();
                    mBottomLayoutInSide.setNameText(name);
                    mBottomLayoutInSide.setType(TYPE_NAME);
                    mBottomLayoutInSide.setVisibility(View.VISIBLE);
                    mBottomLayoutInSide.startAnimation(getBottomInUpToDown());
//                    mBottomLayoutBeauty.setVisibility(View.GONE);
                } else {
                    mBottomLayoutInSide.setNameText(name);
                    mBottomLayoutInSide.setType(TYPE_NAME);
                    mBottomLayoutInSide.showTextWithAnim();
                }

            } else {
                mBottomLayoutInSide.setNameText(name);
            }
        }
        if (mBottomLayoutInSide.getVisibility() == View.GONE || mBottomLayoutInSide.getVisibility() == View.INVISIBLE) {
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mBottomLayoutInSide.startAnimation(getBottomInUpToDown());
//            mBottomLayoutBeauty.setVisibility(View.GONE);
        }
    }

    public void showOperationBarWithAnim(int id, int progress, int color) {
        /*if (id == R.id.addemoji) {
            showInsideBottomBarWithButton();
        } else */
        if (id == R.id.filter) {
            if (mBottomLayoutInSide == null || mBottomLayoutInSide.getType() != BottomInsideBarView.TYPE_PROGRESS) {
                if (mBottomLayoutInSide == null) {
                    initBottomLayoutInSide();
                    mBottomLayoutInSide.setProgress(progress);
                    mBottomLayoutInSide.setType(BottomInsideBarView.TYPE_PROGRESS);
                    mBottomLayoutInSide.setVisibility(View.VISIBLE);
                    mBottomLayoutInSide.startAnimation(getBottomInUpToDown());
//                    mBottomLayoutBeauty.setVisibility(View.GONE);
                } else {
                    mBottomLayoutInSide.setProgress(progress);
                    mBottomLayoutInSide.setType(BottomInsideBarView.TYPE_PROGRESS);
                    mBottomLayoutInSide.showProgressbarWithAnim();
                }

            } else {
                mBottomLayoutInSide.setProgress(progress);
            }
        }
        if (mBottomLayoutInSide.getVisibility() == View.GONE || mBottomLayoutInSide.getVisibility() == View.INVISIBLE) {
            mBottomLayoutInSide.setVisibility(View.VISIBLE);
            mBottomLayoutInSide.startAnimation(getBottomInUpToDown());
//            mBottomLayoutBeauty.setVisibility(View.GONE);
        }
    }

    public void hideOperationBarWithAnim(int id) {
        if (/*id == R.id.addemoji || */id == R.id.filter) {
            mBottomLayoutInSide.setVisibility(View.GONE);
//            mBottomLayoutBeauty.setVisibility(View.VISIBLE);
//            mBottomLayoutBeauty.startAnimation(getBottomIn());
        }
    }

    public void showTopViewWithAnimWhenBottomBarHide() {
        if (mTopView.getVisibility() == View.GONE) {
            mTopView.startAnimation(getTopIn());
            mTopView.setVisibility(View.VISIBLE);
        }
    }

    Animation bottomOut;

    public void doHideOperationBarAnim() {
        if (bottomOut == null) {
            bottomOut = AnimationUtils.loadAnimation(this, R.anim.bottom_out);
            bottomOut.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    mBottomOperationViewContainer.setVisibility(View.GONE);
                    mBottomLayoutInSide.setVisibility(View.GONE);
                    showOperationsViewByTabId(mCurId);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        if (!isNeedGoToBeauty()) {
            mBottomOperationViewContainer.startAnimation(bottomOut);
        } else {
            mBottomLayoutInSide.setVisibility(View.GONE);
        }
        /*if (mIsNeedGoToBeauty){
            mBottomLayoutBeauty.setVisibility(View.VISIBLE);
            mBottomLayoutBeauty.startAnimation(getBottomIn());
        }else */
        {
            mBottomLayoutOutSide.setVisibility(View.VISIBLE);
            mBottomLayoutOutSide.startAnimation(getBottomIn());
        }
    }

    //生成背景和贴纸背景
    private void createBackgroundBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 25);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 25, true);
        }

        //stickerBg
        mStickerViewBg = Bitmap.createBitmap(ImageHelper.SCREEN_WIDTH, (int) ComponentContext.getContext().getResources().getDimension(R.dimen.image_edit_emoji_panel_height), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(mStickerViewBg);
        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        int bitmapHeight = (int) (mStickerViewBg.getHeight() * blurBitmap.getWidth() * 1.0f / ImageHelper.SCREEN_WIDTH);
        canvas.drawBitmap(blurBitmap, new Rect(0, blurBitmap.getHeight() - bitmapHeight, blurBitmap.getWidth(), blurBitmap.getHeight()), new Rect(0, 0, mStickerViewBg.getWidth(), mStickerViewBg.getHeight()), bitmapPaint);
        canvas.drawColor(getResources().getColor(R.color.sticker_bg_cover));

        //background
        mBackgroundBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBackgroundBitmap);
        bitmapPaint.setAlpha(30);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);

        blurBitmap.recycle();
    }

    @Override
    public boolean isSupport(int type) {
        switch (type) {
            case BaseOnlineManager.STORE_FUNC_TYPE_FILTER:
                return true;
        }
        return false;
    }

    @Override
    public void finish() {
        super.finish();
        if(!mOnSaveOperation && mExitAdProvider != null) {
            mExitAdProvider.showAd(null);
        }
    }

    private void onExit() {
        if (mExitAdProvider != null) {
            TaskRunnable taskRunnable = new TaskRunnable(TaskRunnable.TYPE_MAIN) {
                @Override
                public void run() {
                    finish();
                }
            };
            mExitAdProvider.showAd(taskRunnable);
        } else {
            finish();
        }
        EditCompleteAdProvider.statistics("exit", "where", "image");
        statisticsMainBtnEditBack();
        //通知栏更新
        NotifyStoreUpdateStatisticUtil.clear();
        finish();
    }

    private void onSave(TaskRunnable taskRunnable) {
        if(mAdProvider != null) {
            mOnSaveOperation = true;
            mAdProvider.onSave(taskRunnable, "image");
        } else {
            if (taskRunnable != null) {
                taskRunnable.runSelfAdaptation();
            }
        }
    }

    public boolean isNeedGoToBeauty() {
        return mIsNeedGoToBeauty;
    }

    public boolean isNeedSave() {
        return mNeedSave;
    }

    public void setNeedSave(boolean needSave) {
        mNeedSave = needSave;
    }

    public void statisticsMainBtnEditBack() {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnEditCancel(mMainButtonEntrance);
        }
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_BACK);
    }

    public void statisticsSave() {

        Watermark watermark = mWatermarkManager.getCurrentWatermark();
        if (mWaterMarkIsExist && watermark != null) {
            StatisticsUtils.statisticsCustomPreviewClick(watermark.getStatisticName());
        }
        if (mCanvasEditTextView != null) {
            mCanvasEditTextView.statistics();
        }
        if (mEraserUsed) {
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_ERASER_SAVE);
        }
        if (mMixerUsed) {
            StatisticsUtils.statisicsCustomFunction(StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_PREVIEW_VALUE_EDITOR_MIXER_SAVE);
        }

        if (mBeautyBarView != null && mBeautyBarView.isHasUseBoobJob()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "boobjob");
        }
        if (mBeautyBarView != null && mBeautyBarView.isHasUseButtocks()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "buttocks");
        }

        if (mBeautyBarView != null && mBeautyBarView.isHasUseRetouch()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "retouch");
        }

        if (mBeautyBarView != null && mBeautyBarView.isHasUseSmooth()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "smooth");
        }

        if (mBeautyBarView != null && mBeautyBarView.isHasUseHairColor()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "hairdye");
        }

        if (mBeautyBarView != null && mBeautyBarView.isHasWhitenUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "whiten");
        }

        if (mBeautyBarView != null && mBeautyBarView.isHealingUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "healing");
        }

        if (mBeautyBarView != null && mBeautyBarView.isEyeTuneUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "eyetune");
        }

        if (mBeautyBarView != null && mBeautyBarView.isLipStickeUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "lip stick");
        }

        if (mBeautyBarView != null && mBeautyBarView.isEyeShadowUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "eye shadow");
        }

        if (mBeautyBarView != null && mBeautyBarView.isEyeLashUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "eye lash");
        }

        if (mBeautyBarView != null && mBeautyBarView.isContactLenseUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "contact lense");
        }

        if (mBeautyBarView != null && mBeautyBarView.isMaleAbsUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "male abs");
        }

        if (mBeautyBarView != null && mBeautyBarView.isPecsUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "pecs");
        }

        if (mBeautyBarView != null && mBeautyBarView.isBicepUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "bicep");
        }

        if (mBeautyBarView != null && mBeautyBarView.isFemaleAbsUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "female abs");
        }

        if (mBeautyBarView != null && mBeautyBarView.isTallerUsed()) {
            StatisticsUtils.statisicsCustomFunction(STATISTIC_EVENT_EDITPAGE, STATISTIC_KEY_FUNCTION_USED, "taller");
        }

        statisticsMainBtnEditSave();

        //内容更新通知栏  sticker filter
        NotifyStoreUpdateStatisticBean notificationStatisticBean = AppApplication.getApplication().getNotifyStoreContentStatisticBean();
        if (notificationStatisticBean != null) {
            String pkgName = notificationStatisticBean.pkgName;
            if (mUsedStickerAndFilter != null && !TextUtils.isEmpty(pkgName)) {
                for (String name : mUsedStickerAndFilter) {
                    if (pkgName.equals(name)) {
                        notificationStatisticBean.statisticSave(name);
                    }
                }
            }
        }
    }

    public void statisticsMainBtnEditSave() {
        if (TextUtils.isEmpty(mMainButtonEntrance)) {
            return;
        }
        statisticsMainBtnEditSave("save");
        StringBuilder useTools = new StringBuilder();
        if (mStickerUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_STICKERS);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("sticker");
        }
        if (mFilterUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_FILTER);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("filter");
        }
        if (mCropUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_CROP);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("crop");
        }
        if (mAdjustUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_ADJUST);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("adjust");
        }
        if (!mIsNeedGoToBeauty && mWaterMarkIsExist) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_WATERMARK);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("watermark");
        }
        if (mTextUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_TEXT);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("text");
        }
        if (mDoodleUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_DOODLE);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("doodle");
        }
        if (mMixerUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_BLEND);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("mixer");
        }
        if (mMirrorUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_MIRROR);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("mirror");
        }
        if (mBlurUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_BLUR);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("blur");
        }
        if (mRotateUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_ROTATE);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("rotate");
        }
        if (mBeautyUsed) {
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_BEAUTY);
            useTools.append(StatisticsConstant.EDIT_TOOL_VALUE_LINE);
            statisticsMainBtnEditSave("beauty");
        }
//        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_EDIT_PAGE_SAVE, StatisticsConstant.KEY_EDIT_TOOL, useTools.toString());
        if (mIsNeedGoToBeauty) {
            getBeautyBarView().statisticsSave();
        }
    }

    public void statisticsMainBtnEditSave(String useWhat) {
        if (!TextUtils.isEmpty(mMainButtonEntrance)) {
            StatisticsUtils.statisticsMainBtnEditSave(mMainButtonEntrance, useWhat);
        }
    }

    public boolean editOperationBarCanceled(int operationBarId) {
        boolean result = true;
        switch (operationBarId) {
            case R.id.crop:
                mFilterCallBackListener.cancel();
                mCropBarView.setVisibility(View.GONE);
                break;
            case R.id.adjust:
                if (getAdjustBarView().cancelFilter()) {
                    //只有在显示adjust的情况下才能最终cancel
                    showInsideBottomBarWithName(R.string.image_edit_adjust, View.NO_ID);
                    setConfirmEnable(getAdjustBarView().isModified());
                    result = false;
                } else {
                    mFilterCallBackListener.cancel();
                }
                break;
            case R.id.watermark:
                Watermark watermark = null;
                if (mHasUserModify || !mHasDateMark) {
                    watermark = mWatermarkManager.getCurrentWatermark();
                }
                if (mWatermarkManager.isPlaceholderWatermark(watermark)) {//没有水印
                    mWaterMarkIsExist = false;
                    mWaterMarkIV.setImageBitmap(null);
                } else {
                    mWaterMarkIsExist = true;
                    Bitmap bitmap = mWatermarkManager.getWatermarkBitmap(watermark);
                    if (bitmap != null) {
                        mWaterMarkIV.setImageBitmap(bitmap);
                    }
                }
                mWatermarkManager.setTempWatermark(null);
                refreshWaterMark();
                break;
            case R.id.addtext:
                mCanvasEditTextView.reset();
                mFilterCallBackListener.cancel();
                break;
            case R.id.doodle:
                mGraffitoView.reset();
                mFilterCallBackListener.cancel();
                break;
            case R.id.op_mixer:
                if (mMixerBarView != null && mMixerBarView.onCancelClick()) {
                    if (openEraseForMixer(false, false)) {
                        result = false;
                        break;
                    }
                    mImageMixerView.reset();
                    getMixerBar().reset();
                    resetGPUImageView();
                } else {
                    result = false;
                }
                break;
            case R.id.mirror:
                mMirrorBarView.reset();
                break;
            case R.id.tilt_shift:
                getTiltShiftBarView().cancel();
                mFilterCallBackListener.cancel();
                break;
            case R.id.rotate:
                if (mRotateBarView != null) {
                    mRotateBarView.restore();
                }
                mFilterCallBackListener.cancel();
                break;
            default:
        }
        return result;
    }

    public void editOperationBarConfirmed(int operationBarId) {
        switch (operationBarId) {
            case R.id.crop:
                mCropBarView.setVisibility(View.GONE);
                break;
            case R.id.adjust:
                mAdjustBarView.setVisibility(View.GONE);
                break;
            case R.id.watermark:
                mWaterMarkBarLayout.setVisibility(View.GONE);
                break;
            case R.id.addtext:
                mAddTextView.setVisibility(View.GONE);
                break;
            case R.id.doodle:
                mDoodleBarView.setVisibility(View.GONE);
                break;
            case R.id.op_mixer:
                mImageMixerView.setVisibility(View.GONE);
                mImageEraserView.setVisibility(View.GONE);
                break;
            case R.id.mirror:
                mMirrorBarView.setVisibility(View.GONE);
                break;
            case R.id.tilt_shift:
                mTileShiftView.setVisibility(View.GONE);
                break;
            case R.id.rotate:
                mRotateBarView.setVisibility(View.GONE);
                break;
            default:
        }
    }

    public void updateSrcBitmap(CameraDrawable bitmap) {
        mSrcBitmap = bitmap;
    }

    public ImageView getWatermarkIV() {
        return mWaterMarkIV;
    }

    public void showMixerInEdit() {
        int childcount = mEditOperationViewContainer.getChildCount();
        for (int index = 0; index < childcount; index++) {
            View childView = mEditOperationViewContainer.getChildAt(index);
            childView.setVisibility(View.GONE);
        }
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING | WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        getEraserBar().setVisibility(View.GONE);
        getMixerBar().setVisibility(View.VISIBLE);
    }

    public void updateSrcBitmapOfEdit(CameraDrawable cd) {
        getEditOperationBar().updateSrcBitmap(cd);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onExitAddTextFunction(ExitAddTextFuntionEvent event) {
        onCancelClick();
    }

    private View mVipMaskView;
    private View mVipMaskWatchVideoView;
    private AnimationDrawable mVipAnmDrawable;
    private ImageView mVipMaskBgView;
    private FilterBean currentFilterBean;
    private boolean filterDetailUnolockSucc;

    /**
     * 应用滤镜之后调用 是否显示vip mask
     */
    private void checkVipRes(boolean artistFilter) {
        if (mFilterView != null) {
            currentFilterBean = mFilterView.getCurrentFilterBean();
            if (currentFilterBean != null) {
                //开始算显示模糊页的次数
                if (!AppVipManager.isVip()&&currentFilterBean.isBuy()) {
                    SPDataManager.showTodayNorStickersSubscribeMask();
//                    SPDataManager.showTodayAllSubscribeMask();
                }
                showFilterVipMask(currentFilterBean.isBuy(), artistFilter);

            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getFilterDetailUnlockFilterName(FilterDetailUnlockSuccess event){
        if(mUnlockFilter!=null){
            mUnlockFilter.add(event.name);
        }
    }

    private void showFilterVipMask(boolean show, boolean artistFilter) {
        if (AppVipManager.isVip()) {
            show = false;
        }
        if (mUnlockFilter.contains(mFilterView.getCurrentFilterName2())) {
            show = false;
        }

        if (mVipMaskView == null) {
            ViewStub viewById = findViewById(R.id.viewstub_vip_mask);

            mVipMaskView = viewById.inflate();
            AppCompatTextView textView=mVipMaskView.findViewById(R.id.tv_vip_get_result);
            measureTextViewSize(this,textView,200);
            mVipMaskBgView = mVipMaskView.findViewById(R.id.vip_mask_bg);
            mVipMaskView.setClickable(true);
            mVipAnmDrawable = (AnimationDrawable) ((ImageView) mVipMaskView.findViewById(R.id.iv_vip_btn_anim)).getDrawable();

            mVipMaskView.findViewById(R.id.tv_vip_get_result).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    SPDataManager.showTodayAllSubscribeMask();
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_BUTT_CLICK,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                            StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                    backFromMaterialVipSubs = true;
                    SVipController.showFunctionSubscribe(EditorImageActivity.this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_FILTER,null);
                }
            });
            mVipMaskWatchVideoView = mVipMaskView.findViewById(R.id.tv_video_get_result);
            mVipMaskWatchVideoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                            StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                    SpUtils.obtain().save(ISFROMBUTTON, true);
                    SpUtils.obtain().save(EFFECT_NAME, currentFilterBean.getName());
                    getRewardAdManager().showRewardAdVideo();
                }
            });

            if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
                DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                        "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
                mVipMaskWatchVideoView.setVisibility(View.GONE);
            }


//            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//            if (SPDataManager.isFirstCloseSubsPage() || (beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT)) {
//                mVipMaskWatchVideoView.setVisibility(View.GONE);
//            }
//            if (mVipMaskWatchVideoView.getVisibility() == View.VISIBLE){
//                if (getEditTool().equals("filter")){
//                    //素材
//                }else{
//                }
//            }
        }

        if (show) {
            if (artistFilter) {
                mVipMaskView.setVisibility(View.INVISIBLE);
                try {
                    mContentView.setDrawingCacheEnabled(true);
                    mContentView.buildDrawingCache();
                    Bitmap ret = Bitmap.createBitmap(mContentView.getDrawingCache());
                    mContentView.destroyDrawingCache();
                    mContentView.setDrawingCacheEnabled(false);
                    Bitmap blur = BlurUtil.blur(ComponentContext.getContext(), ret, 20);
                    mVipMaskBgView.setImageBitmap(blur);
                } catch (Throwable e) {

                }
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                        StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                mVipMaskView.setVisibility(VISIBLE);
                mVipAnmDrawable.start();
            } else {
                ThreadPool.runOnNonUIThread(new Runnable() {
                    @Override
                    public void run() {
                        final Bitmap currentBitmap = GPUImage.getBitmapForFilter(mSrcBitmapCopy, mFilterView.newCurrentFilter());
                        ThreadPool.runUITask(new Runnable() {
                            @Override
                            public void run() {
                                mCoverImageView.setImageBitmap(currentBitmap);
                                mVipMaskView.setVisibility(View.INVISIBLE);
                                try {
                                    mCoverImageView.setVisibility(VISIBLE);
                                    mContentView.setDrawingCacheEnabled(true);
                                    mContentView.buildDrawingCache();
                                    Bitmap ret = Bitmap.createBitmap(mContentView.getDrawingCache());
                                    mContentView.destroyDrawingCache();
                                    mContentView.setDrawingCacheEnabled(false);
                                    mCoverImageView.setVisibility(View.INVISIBLE);
                                    Bitmap blur = BlurUtil.darkBlur(ComponentContext.getContext(), ret, 20);
                                    mVipMaskBgView.setImageBitmap(blur);
                                } catch (Throwable e) {
                                    mVipMaskBgView.setBackgroundResource(R.drawable.ic_filter_vip_mask);
                                }

                                //显示模糊页统计
                                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                                        StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());

                                if(mVipMaskWatchVideoView.getVisibility()==View.VISIBLE){
                                    //模糊页上观看视频按钮可见时统计
                                    StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                                            StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                                            StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_MATERIAL,
                                            StatisticsConstant.KEY_FILTER_NAME,currentFilterBean.getName());
                                }
                                mVipMaskView.setVisibility(VISIBLE);
                                mVipAnmDrawable.start();

                                if (!AppVipManager.isVip()) { //非订阅非model
                                    if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
                                        DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                                                "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
                                        backFromMaterialVipSubs = true;
                                        SVipController.showFunctionSubscribe(EditorImageActivity.this, VIP_ENTRANCE_EDIT, StatisticsConstant.ENTRANCE_VALUE_FILTER,null);

                                    } else {
                                        DLog.d("wLog", "若是当天第3次及之后进入模糊页，则直接在模糊页显示激励视频按钮，" +
                                                "并不主动跳转主订阅页；");
                                    }
                                }


                            }
                        });
                    }
                });
            }
        } else {
            mVipMaskView.setVisibility(View.GONE);
            mVipAnmDrawable.stop();
        }
    }
    private boolean mRewardAdLoading;
    private RewardAdManager mRewardAdManager;
    public RewardAdManager getRewardAdManager() {
        if (mRewardAdManager == null) {
            initAd();
        }
        return mRewardAdManager;
    }

    private void initAd() {
        mRewardAdManager = new RewardAdManager(this, AdKeyConstant.ADMOB_REWARDED_VIDEO,
                AdKeyConstant.UNITY_REWARDED_VIDEO, AdKeyConstant.REWARDED_VIDEO_ID);
        mRewardAdManager.setShowOverTimeMills(20000L);
        mRewardAdManager.setRewardListener(new RewardAdManager.RewardListener() {
            @Override
            public void onReward() {
                //激励完成,设置一次vip
                SPDataManager.setAdOneTimeVip(true);
                check2SaveVip(true);
                if (mCurId == R.id.filter) {
                    mUnlockFilter.add(mFilterView.getCurrentFilterName2());
                } else if(mCurId == R.id.sticker) {
                    StickerUnlockData.getInstance().unlockSticker(SpUtils.obtain().getString(EFFECT_NAME, ""));
                    refreshSticker(new RefreshStickerEvent(RefreshStickerEvent.OPERATION_REFRESH));
                }
                mRewardAdLoading = false;
                if (mFromMaterialVip) {//针对滤镜素材
                    DialogStatistic.adVideoUnlock(0);
                } else if(SpUtils.obtain().getBoolean(SpConstant.IS_UNLOCK_STICKERS,false)){//针对贴纸
                    DialogStatistic.adVideoUnlock(7);
                    SpUtils.obtain().save(SpConstant.IS_UNLOCK_STICKERS,false);
                }else{//针对其他的工具---Bauty等
                    DialogStatistic.adVideoUnlock(1);
                }
            }

            @Override
            public void onFaild() {
                ToastUtil.showToast("loading advance fail");
                if (mRewardAdLoading) {
                    mRewardAdLoading = false;
                    if (CommercializeSDK.TestUser.isTestUser()) {
                        //激励完成，重走报告页逻辑
                        onSubscribeSuccessEvent(new SubscribeSuccessEvent(SubscribeSuccessEvent.SUB_TYPE_ONE_TIME));
                    }
                    ThreadPool.runUITask(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(R.string.reward_ad_load_failed);
                        }
                    });
                }
            }

            @Override
            public void onTimeOut() {
                //超时按照激励处理
                onReward();
            }
        });

        //WiFi环境下，预加载广告视频
        if (NetworkUtils.isWifi() && !AppVipManager.isVip()){
            mRewardAdManager.loadRewardVideoAd();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubscribeSuccessEvent(SubscribeSuccessEvent event) {
        if (mFilterView != null && mFilterView.getFilterAdapter() != null) {
            mFilterView.getFilterAdapter().setVip(true);
            mFilterView.getFilterAdapter().notifyDataSetChanged();
        }
        if(mCurId == R.id.sticker) {
            refreshSticker(new RefreshStickerEvent(RefreshStickerEvent.OPERATION_REFRESH));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReachGPEvent(ReachGPEvent event) {
        if (mFilterView != null && mFilterView.getFilterAdapter() != null) {
            mFilterView.getFilterAdapter().setVip(true);
            mFilterView.getFilterAdapter().notifyDataSetChanged();
        }
    }

}
